如果未在Twig模板的本地范围中定义全局变量,是否可以回退到全局变量?

时间:2015-02-23 13:55:35

标签: json twig

说我跟随_teaser.twig部分:

<article>
  <h2> {{ article.headline }} </h2>
  <p> {{ article.lede }} </p>
  {% if {{article.byline }} %}
    <address>{{ article.byline }}</address>
  {% endif %}
</article>

我包括以下方式:

<aside>
  {% for article in teasrs %}
    {% include '_teaser.twig' %}
  {% endfor %}
</aside>
<section>
  {% for article in opinion.items %}
    {% include '_teaser.twig' %}
  {% endfor %}
<section>

json文件中使用以下数据结构:

{
  "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中一样。

所需的输出是:

<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无法提供帮助。

1 个答案:

答案 0 :(得分:0)

使用默认管道

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

<article>
  <h2> {{ article.headline|default('default value) }} </h2>
  <p> {{ article.lede|default('default value) }} </p>
</article>
相关问题