You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mustache:如何仅读取当前上下文中的同名变量

Mustache 仅访问当前上下文同名属性的解决方案

Mustache 的上下文查找机制是向上冒泡的——当当前上下文找不到指定属性时,会自动去父级上下文查找,这就导致了你遇到的问题:Facebook 条目没有 href,但渲染时会取到父级的 http://example.com,使得 {{^href}} 分支永远不会触发。

原生 Mustache 没有直接限定仅查找当前上下文的语法,但可以通过自定义 Lambda 函数实现这个需求,无需修改原有属性名。

解决方案步骤

1. 在数据中添加 Lambda 函数

添加一个名为 local 的 Lambda,用于检查当前上下文是否存在指定属性:

{
   title: 'Hello World',
   href: 'http://example.com',
   socials: [
      {
         label: 'Twitter',
         href: 'http://twitter.com'
      },
      {
         label: 'Facebook',
      }
   ],
   local: function(prop) {
      return function() {
         // 仅返回当前上下文的属性,不存在则返回 false
         return this[prop] !== undefined ? this[prop] : false;
      }
   }
}

2. 修改模板逻辑

用自定义的 local Lambda 替代直接的 {{#href}} 判断,确保仅检查当前上下文:

<div>
   <h1>{{title}}</h1>
   <a href="{{href}}">{{href}}</a>
   <ul>
      {{#socials}}
         <li>
            {{#local 'href'}}
               <a href="{{href}}">{{label}}</a>
            {{/local 'href'}}

            {{^local 'href'}}
               {{label}}               
            {{/local 'href'}}
         </li>
      {{/socials}}
   </ul>
</div>

为什么 {{.href}} 无效?

{{.}} 在 Mustache 中代表当前上下文的完整对象,但它仅能直接输出对象的字符串形式,不支持通过 {{.href}} 这种链式语法访问对象属性,所以无法实现你的需求。

内容的提问来源于stack exchange,提问作者E-g

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 12:40:12