如何在NodeJS和PUG中允许将纯文本过滤为HTML标签? [英] How to allow filtering of plain-text into HTML tags in NodeJS and PUG?

查看:189
本文介绍了如何在NodeJS和PUG中允许将纯文本过滤为HTML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在NodeJS和PUG/Jade中有一个Web应用程序.我想将由开发人员控制的应用程序逻辑与由营销人员和翻译人员控制的文本内容分开,同时保持所有源代码的集成. (我问过这种分离方法

I have a web application in NodeJS and PUG/Jade. I want to separate the logic of the application, controlled by a developer, from the textual content, controlled by a marketing person and translators, while keeping all the source code integrated. (I asked about ways for this separation here and got no answers as of this writing).

对于英语,我将JSON对象en.json用于:

For English, I use a JSON object en.json with:

{
  "404": {
    "notFound": "Page not found"
  }
}

控制器将其加载:

let localText = require('./en.json');
res.status(404).render('404', {
  text: localText
});

,然后视图将其呈现为:

and the view renders it with:

h1 #{text['404'].notFound}

我想在JSON对象中包含链接,例如:

I would like to include links in the JSON object, such as:

{
  "404": {
    "notFound": "Page not found. Go to <a href=\"www.twitter.com\">Twitter</a>, maybe?"
  }
}

NodeJS使用源代码而不是链接来呈现页面.我将它分为三个部分来临时修复它:

NodeJS renders the page with the source code and not the link. I've fixed it temporarily by splitting into three:

{
  "404": {
    "notFound1": "Page not found. Go to",
    "notFound2": "Twitter",
    "notFound3": ", maybe?"
  }
}

和视图:

h1 #{text['404'].notFound1} #[a(href="www.twitter.com") #{text['404'].notFound2}] #{text['404'.notFound3}

现在它变得很难维护.

我了解此页面,我可以创建一个过滤器来预处理所有链接,例如:

I understand from this page that I could create a filter to pre-process all links, e.g.:

options.filters = {
  'my-own-filter': function (text) {
    text = text.replace("Twitter", "<a href=\"www.twitter.com\">Twitter</a>")
    /* all other replacements */
    return text;
  }
};

我找不到如何将此类过滤器选项传递给Web应用程序的方法,该Web应用程序的唯一PUG行是app.set('view engine', 'pug');.

I couldn't find how to pass such filter options to the web application, whose only PUG line is app.set('view engine', 'pug');.

如何使用NodeJS和Jade预处理纯文本以填充链接并将其很好地显示给浏览器用户?

How can I pre-process a plain-text with NodeJS and Jade to populate links and display them nicely to the browser user?

推荐答案

您应该可以使用未转义的字符串插值语法(a)而不是常规的字符串插值语法(c5)来使HTML正确呈现.

You should be able to use unescaped string interpolation syntax (!{variable}) instead of the regular string interpolation syntax (#{variable}) to get the HTML to render correctly.

在您的情况下:

h1 !{text['404'].notFound}

但是请记住 Pug文档:

警告

请记住,如果未转义的内容来自用户,则将未转义的内容缓冲到模板中可能会带来很大的风险.永远不要相信用户的输入!

Keep in mind that buffering unescaped content into your templates can be mighty risky if that content comes fresh from your users. Never trust user input!

这篇关于如何在NodeJS和PUG中允许将纯文本过滤为HTML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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