展开变量内的标签

Expand tags inside variable

有没有办法让 Mustache 扩展变量内的标签?

我明白这就是partials的目的。但是,正如您在下面的示例中看到的那样,由于视图的结构,有时使用局部变量是不切实际的。

如果不是,我应该如何更改下面视图的结构?目前我提前渲染每个条目的html 属性。这似乎并不理想(并且破坏了更改 Mustache 的定界符等功能)。

例子

博客主页的视图:

var view = {
   title: 'Example blog',
   entries: [
     {url: '/a', html: '<p>The first entry on {{title}}</p>'},        
     {url: '/b', html: '<p>The second entry on {{title}}</p>'},     
     {url: '/c', html: '<p>The third entry on {{title}}</p>'}
   ]
};

对应模板:

{{#entries}}
  {{{html}}}
{{/entries}}

调用 Mustache.render 后,我收到了这个。

<p>The first entry on {{title}}</p>        
<p>The second entry on {{title}}</p>
<p>The third entry on {{title}}</p>

我想收到这个:

<p>The first entry on Example blog</p>        
<p>The second entry on Example blog</p>
<p>The third entry on Example blog</p>

试试这个:

var view = {
   title: 'Example blog',
   entries: [
     {url: '/a', position: 'first'},        
     {url: '/b', position: 'second'},     
     {url: '/c', position: 'third'}
   ]
};

{{#entries}}
  <p>The {{position}} entry on {{title}} blog</p>
{{/entries}}

Mustache 不会这样做,而且您不希望它这样做。叫做"mustache injection"相当于SQL注入

当 Twitter 首次开始使用 Mustache 客户端时,出现了一种攻击,即在推文中发布带有 Mustache 标签的 URL 会导致查看该推文的任何人转发该推文。修复是为了防止 Mustache 双重扩展标签。