首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果没有在Twig模板的局部作用域中定义全局变量,是否可以回退到全局变量?

如果没有在Twig模板的局部作用域中定义全局变量,是否可以回退到全局变量?
EN

Stack Overflow用户
提问于 2015-02-23 21:55:35
回答 1查看 43关注 0票数 0

假设我有以下_teaser.twig partial:

代码语言:javascript
复制
<article>
  <h2> {{ article.headline }} </h2>
  <p> {{ article.lede }} </p>
  {% if {{article.byline }} %}
    <address>{{ article.byline }}</address>
  {% endif %}
</article>

其中包括以下几种方式:

代码语言:javascript
复制
<aside>
  {% for article in teasrs %}
    {% include '_teaser.twig' %}
  {% endfor %}
</aside>
<section>
  {% for article in opinion.items %}
    {% include '_teaser.twig' %}
  {% endfor %}
<section>

json文件中包含以下数据结构:

代码语言:javascript
复制
{
  "article": {
    "headline": "A short headline",
    "lede": "A short descriptive lede paragraph"accusantium"
  },
  "teasers": {
    "article1": {
      "headline": "Some headline",
      "lede": "A lede that describes the article, but without revealing too much, so that users still have a reason to click"
    }, 
    "article2": {}
  },
  "opinion": {
     "article": {
       "byline": "Anonymous"
     },
     "items": {
       "article1: {},
       "article2: {}
     }
  }
}

理想情况下,我希望变量解析增加作用域,就像在Mustache中一样。

所需的输出为:

代码语言:javascript
复制
<aside>
  <article>
    <h2> Some headline </h2>
    <p> 
      A lede that describes the article,
      but without revealing too much, so that 
      users still have a reason to click
    </p>
  </article>
  <article>
    <h2> A short headline </h2>
    <p> A short descriptive lede paragraph </p>
  </article>
</aside>
<section>
  <article>
    <h2> A short headline </h2>
    <p> A short descriptive lede paragraph </p>
    <address>Anonymous</address>
  </article>
  <article>
    <h2> A short headline </h2>
    <p> A short descriptive lede paragraph </p>
    <address>Anonymous</address>
  </article>
<section>

除非我遗漏了什么,否则使用default()过滤器指定默认内容是不可取的,因为我希望默认内容派生自模型,而不是视图。例如,在预告中,我不想有一个备用署名,但在评论部分,我希望总是显示一个署名,带有备用到Anonymous的署名,对于这一点,使用default无济于事。

EN

回答 1

Stack Overflow用户

发布于 2015-02-23 22:16:55

使用默认管道

文档http://twig.sensiolabs.org/doc/filters/default.html

代码语言:javascript
复制
<article>
  <h2> {{ article.headline|default('default value) }} </h2>
  <p> {{ article.lede|default('default value) }} </p>
</article>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28675393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档