使用handlebars.js获取动态用户内容?

时间:2016-11-12 10:26:56

标签: javascript handlebars.js

Handlebars通常用于静态预定义的html模板,然后通过JSON提供动态数据,但是如果模板本身来自json呢?

我正在尝试建立一个社区论坛,我有一个模板可以填写用户发布的位置。然而,帖子本身也包含模板信息(动态)。如何让把手处理刚刚出现在ajax中的动态模板?

例如,用户帖子可以按任何顺序包含以下任何或所有内容:文字,图片,链接,视频等。

内容将如下所示:

  

{{text-open}} blablabla heres a picture {{text-close}} {{image-open}}
  http://someRandomUrl.com {{image-close}} {{image-open}}
  http://anotherRandomUrl {{image-close}}

我不知道如何用把手做这件事。我有感觉也许我应该只使用字符串替换功能?但这会是最佳方法吗?

1 个答案:

答案 0 :(得分:0)

您只需要编译模板:

fetch("post.hbs")
    .then(source => Handlebars.compile(source))
    .then(postTemplate => {
        // Do stuff, then fill the template:
        postElement.innerHTML = postTemplate(postData);
    });