如何在NodeJS和PUG中将纯文本过滤到HTML标记中?

问题描述 投票:0回答:1

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

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

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

控制器加载:

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

并且视图使用:

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

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

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

NodeJS使用源代码而不是链接来呈现页面。我已通过拆分为三个临时修复它:

{
  "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}

并且现在变得难以承受。

[我了解from this thread我可以使用降价过滤器:markdown来转换带有PUG链接的源文本,from this page我可以创建一个过滤器来预处理所有链接,例如:

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

首先,我得到一个错误unknown filter ":markdown"。第二,我找不到如何将此类过滤器选项传递给Web应用程序的方法,该Web应用程序的唯一PUG行是app.set('view engine', 'pug');

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

node.js hyperlink pug
1个回答
0
投票

您应该能够使用unescaped string interpolation语法(!{variable})而不是常规字符串插值语法(#{variable})来使HTML正确呈现。

根据您的情况:

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

但是请记住Pug documentation中的警告语:

注意

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

© www.soinside.com 2019 - 2024. All rights reserved.