出于某种原因,我无法理解 mustache 模板并将两个模板合并在一起...
var template = '<div class="thing"><h2>{{head}}</h2><p>{{text}}</p>{{>passwordStrength}}</div>',
partials = {
passwordStrength: '<div class="pStrength"><span>{{weak}}</span><span>{{medium}}</span><span>{{strong}}</span></div>'
},
view = {
email: {
head: 'Email addresses',
text: 'are very useful if you use them properly...'
},
password: {
head: 'Password',
text: 'Put in the password of your choice',
passwordStrength: {
weak: 'Weak',
medium: 'Medium',
strong: 'Strong'
}
}
};
$.mustache(template, view['password'], partials['passwordStrength']);
上面的似乎不起作用,但它是我期望的那种方式。我想将所有文本内容保留在 View 中,以便在此处翻译所有文本。 passwordStrength 'partial/template thingy' 我只想要在呈现密码位时使用。我不太确定这是如何完成的。我试过 {{#passwordStrength}} {{/passwordStrength}} 认为它只会在它存在时呈现,但你必须正确传递部分,那就是 {{>passwordStrength}}。我不希望它一直出现……只有当内容也存在时才出现。我这样做完全错了吗?
我想说我只希望在满足条件时出现一个模板(我们正在查看密码 View ),然后我将逻辑放入我的模板中,这违背了它们的要点......但是passwordStrength 位应该在模板中,所以我对如何处理它感到有点困惑
谢谢,多姆
编辑:Stackoverflow 不允许我回答我自己的问题,我不确定为什么它不允许我这样做,所以我必须用我的答案编辑我的原始问题:
我不需要使用部分......我只需要将 passwordStrength HTML 添加到原始模板并用 {{#passwordStrength}}{{/passwordStrength}} 包装它,这样 IF 它就在那里(就像只有在密码 View 中)然后它将呈现 HTML 并将使用 View 中提供的文本。像这样:
var template = '<div class="thing"><h2>{{head}}</h2><p>{{text}}</p>{{#passwordStrength}}<div class="pStrength"><span>{{weak}}</span><span>{{medium}}</span><span>{{strong}}</span></div>{{/passwordStrength}}</div>',
view = {
email: {
head: 'Email addresses',
text: 'are very useful if you use them properly...'
},
password: {
head: 'Password',
text: 'Put in the password of your choice',
passwordStrength: {
weak: 'Weak',
medium: 'Medium',
strong: 'Strong'
}
}
};
$.mustache(template, view['password']);
最佳答案
您最初遇到问题是因为您没有传递整个 partials
对象。 partials
参数应该是一个对象,其键以您的部分命名,值以模板命名。
你自己的答案是正确的,你可以用 {{#passwordStrength}}
包装它,以便在数据存在时有选择地显示它。
我在 jsFiddle 中调整了您的原始帖子,因此您可以看到它正常工作- http://jsfiddle.net/maxbeatty/GQ2Fj/
我将 HTML 分离出来使 JS 更易于阅读:
<script type="text/html" id="template">
<div class="thing">
<h2>{{head}}</h2>
<p>{{text}}</p>
{{>passwordStrength}}
</div>
</script>
<script type="text/html" id="passwd">
{{#passwordStrength}}
<div class="pStrength">
<span>{{weak}}</span>
<span>{{medium}}</span>
<span>{{strong}}</span>
</div>
{{/passwordStrength}}
</script>
除了传递整个 partials
对象之外,JS 几乎完全相同:
var template = $('#template').html(),
partials = {
passwordStrength: $('#passwd').html()
},
view = {
email: {
head: 'Email addresses',
text: 'are very useful if you use them properly...'
},
password: {
head: 'Password',
text: 'Put in the password of your choice',
passwordStrength: {
weak: 'Weak',
medium: 'Medium',
strong: 'Strong'
}
}
},
html = Mustache.render(template, view['password'], partials);
document.write(html);
关于javascript - Mustache JS 和合并模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7305458/