In order to organize my localization content (ie, .resx files
currently) in a nice way, I would like to be able to do something like
this in view Views:
<div>This is an example of accessing the key "theKey" from the global
resource "Global":</div>
${Html.Resource("Global", "theKey")}
<div>This is an example of accessing the key "theKey" from the local
resource</div>
${Html.Resource("theKey")}
Where Html.Resource() are extension methods to HtmlHelper.
Implementing Html.Resource("Global", "theKey") is pretty easy:
public static string Resource(this HtmlHelper htmlhelper, string file,
string key)
{
return HttpContext.GetGlobalResourceObject(file, key,
Thread.CurrentThread.CurrentCulture).ToString();
}
But I'm having trouble doing the "local" version. Basically, I need to
be able to infer some sort of static to know from which resource file
to read from. I thought that the current original view/partial name
would be available somewhere in HtmlHelper.ViewContext, but I don't
think Spark keeps a reference to the orginal filename anywhere.
So I resorted to include this line in every view/partial where I might
use resources:
# Html.SetResource("nameOfTheViewOrPartial");
where Html.SetResource() is simply:
public static void SetResource(this HtmlHelper htmlHelper, string
file)
{
htmlHelper.ViewData["__resource__"] = file;
}
and thus the local version of Html.Resource() can become:
public static string Resource(this HtmlHelper htmlHelper,
string key)
{
var file = (string) htmlHelper.ViewData["__resource__"];
return
HttpContext.GetGlobalResourceObject(file, key,
Thread.CurrentThread.CurrentCulture).ToString();
}
Is there any way I could somehow automate this process, maybe by
having the original filename of the view embedded in the generated
code?
One drawback of this method is that every .resx files need to go in
App_GlobalResources; I would much prefer having the "local" resources
be closer to the relevant source files, but I haven't been able to get
App_LocalResources to work with Spark yet (haven't really put time in
trying, mind you).
Do you have any other suggestion for managing localization resources?
Maybe I'm missing something obvious as far as organizing and accessing
resources in a clean manner.
Thanks!
I am not sure whther this is a good idea, but I add Resource files to
my app_globalresources folder.
Then I can include them in a page like this :
${Resources.Strings.ToonDetails}
An extra advantage would be intellisense support (although I'm not
sure since I do not have intellisense available atm)
Kind regards,
Tom
Maybe I should just assume that my next provider will produce strongly
typed names, too, and be done with it...
Simon Labrecque