javascript 把手助手 - 返回 HTML 而不是文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20104871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:43:41  来源:igfitidea点击:

Handlebars helper - returning HTML not text

javascripthandlebars.jshelpers

提问by Adrian

I wrote a simple helper for my template. Here's the code:

我为我的模板编写了一个简单的助手。这是代码:

Handlebars.registerHelper('splitQuote', function (string) {
    if (string.indexOf('|') !== -1) {
        return string.replace('|', '<span>') + '</span>';
    }
    return string;
});

So I pass a string, and split the string by '|' character. I also want to put second part into span tags.

所以我传递一个字符串,并用'|'分割字符串 特点。我还想将第二部分放入 span 标签中。

Problem is, the result that is being returned is pure text, so I get span tags like a text, not HTML.

问题是,返回的结果是纯文本,所以我得到了像文本一样的跨度标签,而不是 HTML。

Does anyone know what's the catch?

有谁知道有什么问题?

Tnx

田纳西州

回答by megawac

You have to mark the string as html in your helper if you want to Handlebars not to escape it. Use Handlebars.safeStringto do this. The below should suit your needs

如果你想 Handlebars 不转义它,你必须在你的助手中将字符串标记为 html 。使用Handlebars.safeString要做到这一点。以下应该适合您的需求

Handlebars.registerHelper('splitQuote', function(string) {
    if (string.indexOf('|') !== -1) {
        return new Handlebars.SafeString(string.replace('|', '<span>') + '</span>');
    }
    return string;
});

As mentioned in comments you should probably escape the passed string using Handlebars.Utils.escapeExpression(string)to encode the string before you do your custom formatting. I'd recommend writing like this:

如评论中所述,您可能应该Handlebars.Utils.escapeExpression(string)在进行自定义格式化之前使用对字符串进行编码来转义传递的字符串。我建议这样写:

Handlebars.registerHelper('splitQuote', function(string) {
    string = Handlebars.Utils.escapeExpression(string);
    if (string.indexOf('|') !== -1) {
        string = string.replace('|', '<span>') + '</span>';
    }
    return new Handlebars.SafeString(string); // mark as already escaped
});

回答by Mendes

You don′t need to use SafeString. Instead, use the "triple moustaches" from handlebar:

你不需要使用SafeString. 相反,使用车把上的“三重胡须”:

From Handlebars web site, HTML Escaping section:

来自Handlebars 网站,HTML 转义部分:

Handlebars HTML-escapes values returned by a {{expression}}. If you don't want Handlebars to escape a value, use the "triple-stash", {{{.

Handlebars HTML 转义 {{expression}} 返回的值。如果您不希望 Handlebars 转义值,请使用“triple-stash”,{{{.

So, a simple triple quote in your html will avoid escaping:

因此,html 中的简单三重引号将避免转义:

{{{splitQuote}}}