寻找更清洁的code嵌入文本剃须刀呼叫时 [英] looking for cleaner code when embedding razor calls in text

查看:74
本文介绍了寻找更清洁的code嵌入文本剃须刀呼叫时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经有过这样的事情:

I used to have something like this:

We suggest you read our @Html.ActionLink("help page", "Help", "Home") before
proceeding.

漂亮和干净。于是我决定,我们需要国际化的应用程序。我想不出更好的方式来处理上述要比存储在资源文件中的以下字符串:

nice and clean. then I decided we needed to internationalise the app. I couldn't figure out a better way to deal with the above than to store the following string in the resource file:

We suggest you read our [HelpPage] before proceeding.

,然后在视图我要做的:

and then on the view I have to do:

@MvcHtmlString.Create(this.Resource("Help").ToString()
   .Replace("[HelpPage]",
       @Html.ActionLink("help page", "Help", "Home").ToString()
   )
)

您可以使用哪些其他策略使用剃刀国际化?

What other strategies can you use to internationalize using Razor?

this.Resource()是一个页面的扩展调用 .GetLocalResourceObject()并返回 MvcHtmlString

this.Resource() is a page extension that calls .GetLocalResourceObject() and returns an MvcHtmlString

推荐答案

所以这里是我最后写:

public static class PageExtensions
{
    public static MvcHtmlString Resource(
        this WebViewPage page, string key, 
        Dictionary<string, MvcHtmlString> tokenMap
    ) {
        HttpContextBase http = page.ViewContext.HttpContext;
        string text = (string) http.GetLocalResourceObject(page.VirtualPath, key);
        return new TagReplacer(text, tokenMap).ToMvcHtmlString();
    }

当标签被替换像这样完成的:

where the tag replacements gets done like this:

public class TagReplacer
{
    Dictionary<string, MvcHtmlString> tokenmap;
    public string Value { get; set; } 

    public TagReplacer(string text, Dictionary<string, MvcHtmlString> tokenMap)
    {
        tokenmap = tokenMap;

        Regex re = new Regex(@"\[.*?\]", RegexOptions.IgnoreCase);
        Value = re.Replace(text, new MatchEvaluator(this.Replacer));
    }

    public string Replacer(Match m)
    {
        return tokenmap[m.Value.RemoveSet("[]")].ToString();
    }

    public MvcHtmlString ToMvcHtmlString()
    {
        return MvcHtmlString.Create(Value);
    }
}

所以我的$ C $三我现在可以这样调用:

so in my code I can now call it like this:

@{
   Dictionary<string, MvcHtmlString> tagmap = new Dictionary<string, MvcHtmlString>() {
                { "HelpPage", Html.ActionLink("help page", "Help", "Home") }
            };
}

和其他地方的:

@this.Resource("Help", tagmap)

改进建议最受欢迎

any suggestions for improvement most welcome

这篇关于寻找更清洁的code嵌入文本剃须刀呼叫时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆