Localized Static File Serving
Set up localized static file serving such as images or documents, which dynamically change based on the current locale.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Localized Static Files</title>
<script src="localization.js"></script>
</head>
<body>
<img id="localizedImage" src="" alt="Localized image">
<script>
// Call the function to set the right image based on the browser's locale
setLocalizedImage();
</script>
</body>
</html>
This HTML page includes an image element with an empty `src`. The `localization.js` script is responsible for setting the appropriate image source based on the user's locale.
/* JavaScript (localization.js) */
function setLocalizedImage() {
var userLocale = navigator.language || navigator.userLanguage; // Get the browser's locale
var imagePath = getImagePath(userLocale); // Get the appropriate image path
document.getElementById('localizedImage').src = imagePath; // Set the image source
}
function getImagePath(locale) {
var imageMap = {
'en-US': 'images/image-en.png',
'fr-FR': 'images/image-fr.png',
'es-ES': 'images/image-es.png'
// Add more localized image paths here
};
return imageMap[locale] || 'images/image-default.png'; // Fallback to a default image if the locale is not mapped
}
The `localization.js` file contains two functions. `setLocalizedImage` retrieves the user's locale and sets the image's `src` to the right path using `getImagePath`. `getImagePath` takes the locale as an argument and returns the corresponding image path; if there is no specific image for the locale, it defaults to a generic image.
/* CSS */
#localizedImage {
width: 100%;
max-width: 600px; // Set a max-width for the image if necessary
height: auto; // Maintain aspect ratio
}
The CSS provides styles for the image. It ensures the image scales with the width of its container up to a maximum width and maintains its aspect ratio.