Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 using .resx for localisations of images

I have been using .resx files for localisation of text in my MVC3 app quite happily for a while now following these instructions, but have now got to a point where i need to do localisation of images as well.

the .resx editor in VS2010 will let you add an image as a resource easily enough, it just dumps it in a folder called Resources in the same directory as the .resx file, and i can reference the image in the same way as strings in my views by calling @ResXfileName.ResourceName, but that returns a System.Drawing.BitMap object, i was hoping it would just give me the path to the image so i could shove it in am image tags src attribute, but i can't work out how to get the path at all!

like image 457
Ben Avatar asked Nov 23 '12 14:11

Ben


1 Answers

Solution 1: locale folder structure

The best (and easiest) way would be to add a new HtmlHelper extension method that returns locale name (or LCID) and you can use it with anything afterwards (images, scripts etc.). The best way is of course to have localised files in such folder structure:

/images
    /en-US
        image1.png
    /en-GB
        image1.png
    /es-ES

            image1.png

And this is how you would use it then:

<img src="/images/@Html.Locale/backgrounds/back.png" />

This is an example of such extension method.

public MvcHtmlString Locale(this HtmlHelper helper)
{
    // in case you're setting UI culture
    return MvcHtmlString.Create(System.Threading.Thread.CurrentThread.CurrentUICulture.Name);
}

If this simplification doesn't work in your case and you need specific call for images, then create a UrlHelper method called Image or File where you provide it server app relative path with some tokens that get replaced with your locale name or LCID.

Solution 2: Resource file links

You can also put image paths inside a resource file and use those values in your views to provide correct paths for your images (or other files for that matter).

public MvcHtmlString Resource(this UrlHelper helper, string classKey string resourceKey)
{
    return MvcHtmlString.Create(helper.ViewContext.HttpContext.GetGlobalResourceObject(classKey, resourceKey));
}

And then in your view use it as:

<img src="@Url.Resource("images", "header")" />
like image 58
Robert Koritnik Avatar answered Nov 19 '22 03:11

Robert Koritnik