【问题标题】:Return html tags from json without converting to ascii in express从 json 返回 html 标签而不在 express 中转换为 ascii
【发布时间】:2016-07-17 12:53:03
【问题描述】:

我想在我的 JSON 文件中存储 HTML 标签。这个 JSON 文件就像我的静态 Express 应用程序的数据库,可以存储博文、文本、页面等。

var express = require('express'),
    router  = express.Router();

exports.fsAsync = function fsAsync(callback) {
  fs.readFile(__dirname + '/../database/data.json', 'utf8', (err, data) => {
    if (err) throw callback(err);
    callback(null, JSON.parse(data));
  });
};

/* GET Contact page. */
router.get('/', function(req, res, next) {
  fsAsync(function (err, data) {
    if (err) {
      return res.render('404', {
        title: 'Error 404'
      });
    }
    var contact = data[2].contact;
    res.render('contact', {
      data: contact
    });
  });
});

JSON 文件特定部分:

  {
    "contact": {
      "body": "<p>This is the Contact Page!<br />But maybe I want to store some <a href=\"#\">links</a> in my text also!</p>"
    }
  },

将我的 JSON 中的 html 标签转换为 ascii:

<main class="contact">
  <article>
    &lt;p&gt;This is the Contact Page!&lt;br /&gt;But maybe I want to store some &lt;a href&#x3D;&quot;#&quot;&gt;links&lt;/a&gt; in my text also!&lt;/p&gt;
  </article>
</main><!-- main.about-me -->

有没有办法做到这一点?

模板引擎是express-handlebars:

app.engine('hbs', exphbs({
  extname: 'hbs',
  defaultLayout: 'main',
  // Specify helpers which are only registered on this instance
  helpers: {
    // register hbs helpers in res.locals' context which provides this.locale
    __: function() { return i18n.__.apply(this, arguments); },
    __n: function() { return i18n.__n.apply(this, arguments); }
  }
}));
app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

【问题讨论】:

  • 您的项目中使用了哪个模板引擎?
  • 它是express-handlebars。我更新了我的问题。

标签: javascript html json node.js express


【解决方案1】:

使用把手,您可以使用三重 {{{ }}} 括号获得原始 HTML 输出

<main class="contact">
  <article>
   {{{ body }}}
  </article>
</main>

【讨论】:

  • 很棒的解决方案!我不知道! :)
【解决方案2】:

你需要告诉模板引擎它是html, 在dusts 过滤器将开启自动html编码:

<main class="contact">
  <article>
   {body|s}
  </article>
</main>

【讨论】:

  • 有没有办法通过express-handlebars 实现这一目标?我真的很喜欢这个模板引擎。编辑:有人已经回答了。
【解决方案3】:

我不得不将 html 代码存储在 json 中。 我使用这个网站来格式化 html 并转义必要的字符。

http://www.freeformatter.com/javascript-escape.html

不确定这是否是您要找的,但是,干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 2018-03-24
    • 2022-01-01
    相关资源
    最近更新 更多