javascript - mustache JS : fill multiple divs with different content

标签 javascript mustache

我是第一次使用 Mustache JS,并对实现我想要的效果的最佳方法有疑问。我有以下页面,其中有几个以相同方式设置的 div,但需要获取不同的内容。

my page

这是我到目前为止得到的:

<script id="mustacheTemplate1" type="text/template">
    <div class="{{box_cols}}">
        <div class="box box-{{box_color}}">
            <h2 class="box-title">{{box_title}}</h2>
            {{box_content}}
        </div>
    </div>
</script>

<div class="target-output1"></div>

<script type="text/javascript">
var template1 = $("#mustacheTemplate1").html();
var targetContainer = $(".target-output1");

var shows = { 
    "box_cols": "col-lg-3 col-md-6 col-sm-6",
    "box_color": "blue",
    "box_title": "Title goes here",
    "box_content": "Content goes here",
};

var html = Mustache.to_html(template1, shows);

$(targetContainer).html(html);  
</script>

这填充了我的第一个 div,这就是我想要的。我可以重复此操作并将 target-output1 复制到 target-output2、target-output3 等。但我想知道是否有更好或更有效的方法?

我不知道这是否重要,但我将在某些 div 内容中使用 Google Charts。

最佳答案

假设您拥有用生成的内容填充所需的所有 div,您可以使用循环

var template1 = $("#mustacheTemplate1").html();

[
  { 
    "box_cols": "col-lg-3 col-md-6 col-sm-6",
    "box_color": "blue",
    "box_title": "Title goes here",
    "box_content": "Content goes here",
  },
  { 
    "box_cols": "col-lg-3 col-md-6 col-sm-6",
    "box_color": "red",
    "box_title": "Another Title",
    "box_content": "Totally different content goes here",
  }
  //, ... etc
].forEach(function(data, i) {
  $('.target-output' + (i+1)).html(Mustache.to_html(template1, data))
})

关于javascript - mustache JS : fill multiple divs with different content,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44237148/

相关文章:

javascript - 添加 key :value pair to JSON using javascript

javascript - 如何在 javascript 中使用 C# 代码

jquery - 验证 json 文件中的 Mustache 标签值

templates - 什么是无逻辑模板

javascript - Moustache.js 中的列表和来自 mongodb 的 bson 数据

javascript - 为什么 Chrome 无法使用带有 Javascript 的 insertRule 访问外部样式表?

Windows 7 上 IE11 中的 JavaScriptdialogArguments._IE_PrintType SCRIPT5002 错误

javascript - (我失败了)Javascript 挑战 : function add()()() with closures

javascript - 我的网站上显示无法解释的未定义字符串。不知道如何摆脱它

javascript - 使用 Mustache JS 与胶水连接/连接