从Twig模板中的YAML数据访问嵌套值

时间:2018-11-13 23:19:44

标签: variables twig yaml

我正在尝试访问Twig模板中的嵌套YML数据。我的YML数据的结构如下:

card_default:
  card_title: 'Card Title'
  card_header: 'This is the card header on a multi-part card'
  card_text: "Some quick example text to build on the card title and make up the bulk of the card's content."
  card_link: 'https://github.com/phase2/particle'
  card_background: primary
  card_image_location: top
  card_footer: "This is the card footer"
  text_color: uk-dark
  card_body: "This is some card body text"
  card_style: default
card_image:
  card_more_stuff in here....

...然后我像这样在Twig模板中调用一些数据:

 {% include '@molecules/card/_card.twig' with {
          card_default: {
              card_title: card_title,
              card_text: card_text,
              card_background: 'primary',
              card_link: card_link,
              card_link_text: card_link_text,
              card_link_class: card_link_class,
          }
      } only %}

但这似乎不起作用。我觉得我尝试执行此操作的方式不太正确,但是搜索并没有给我带来更多的见解。本质上,我想访问card_default中的值。

如果我用{{ dump(card_default) }}转储,我可以看到数组中的所有数据

array(14) { ["card_title"]=> string(10) "Card Title" ["card_header"]=> string(44) "This is the card header on a multi-part card" ["card_text"]=> string(94) "Some quick example text to build on the card title and make up the bulk of the card's content." ["card_link"]=> string(34) "https://github.com/phase2/particle" ["card_link_text"]=> string(9) "Read more" ["card_link_class"]=> string(27) "uk-button uk-button-default" ["card_background"]=> string(7) "primary" ["card_width"]=> int(25) ["card_image_location"]=> string(3) "top" ["card_footer"]=> string(23) "This is the card footer" ["list"]=> array(2) { ["list_flush"]=> bool(true) ["items"]=> array(3) { [0]=> array(1) { ["item_text"]=> string(15) "Cras justo odio" } [1]=> array(1) { ["item_text"]=> string(23) "Dapibus ac facilisis in" } [2]=> array(1) { ["item_text"]=> string(18) "Vestibulum at eros" } } } ["text_color"]=> string(7) "uk-dark" ["card_body"]=> string(27) "This is some card body text" ["card_style"]=> string(7) "default" } 

2 个答案:

答案 0 :(得分:0)

数据位于变量card_default中,因此应为例如card_default.card_title
但是您无需创建一个全新的对象,而是可以通过两种方式做到这一点:

YAML

foo:
    bar: 'foobar'
    number: 42

main.twig

{% include "full.twig" with { 'foo' : foo } only %}
{% include "slim.twig" with foo only %}

full.twig

{{ foo.bar }}

slim.twig

{{ number }}

答案 1 :(得分:0)

我发现了这一点,我只需要像这样正确地映射嵌套项目:

  {% include '@molecules/card/_card.twig' with {
      card_title: card_default.card_title,
      card_text: card_default.card_text,
      card_background: 'primary',
      card_link: card_default.card_link,
      card_link_text: card_default.card_link_text,
      card_link_class: card_default.card_link_class,
  }  %}

在上面的代码中,card_default映射到数组的可变部分,即冒号之后。 card_link: card_default.card_link,