首页 > 解决方案 > 如何在 Twig 宏中使用来自 WordPress/Timber 的动态变量

问题描述

我正在为客户网站上的号召性用语链接编写 Twig 宏。以下代码显示了我到目前为止所拥有的内容以及在宏实例中使用双花括号时遇到的问题。

宏 cta.twig 代码

{% macro pill(options={}) %}
  {% set options = {
    class: "",
    link: "",
    title: "",
    text: ""
  } | merge(options) %}
  <a class="cta {{ options.class }}" href="{{ options.link }}" title="{{ options.title }}">{{ options.text }}
    <span>
      <svg role="img" class="arrow arrow--right" width="22" height="18">
        <path d="M9.267 1.206L10.3.29a1.216 1.216 0 0 1 1.577 0l9.046 8.008c.437.388.437 1.014 0 1.398l-9.046 8.012a1.216 1.216 0 0 1-1.577 0l-1.033-.915c-.442-.391-.433-1.03.018-1.413l5.607-4.732H1.52c-.619 0-1.117-.441-1.117-.99V8.341c0-.549.498-.99 1.117-.99h13.373L9.285 2.62c-.456-.383-.465-1.022-.018-1.413z" fill="#FFF"/>
      </svg>
    </span>
  </a>
{% endmacro %}

_html.twig 模板中使用的宏

{{ cta.pill({
  class: "cta--pill cta--no-shadow",
  link: "{{ post.link }}",
  title: "{{ __('View all services', howellsexcavating) }}",
  text: "{{ post.meta( 'module_more_button_text' ) }}"
}) }}

呈现的 HTML

<a class="cta cta--pill cta--no-shadow" href="{{ post.link }}" title="{{ __('View all services', howellsexcavating) }}">
  {{ post.meta( 'module_more_button_text' ) }}
  <span>
    <svg role="img" class="arrow arrow--right" width="22" height="18">
        <path d="M9.267 1.206L10.3.29a1.216 1.216 0 0 1 1.577 0l9.046 8.008c.437.388.437 1.014 0 1.398l-9.046 8.012a1.216 1.216 0 0 1-1.577 0l-1.033-.915c-.442-.391-.433-1.03.018-1.413l5.607-4.732H1.52c-.619 0-1.117-.441-1.117-.99V8.341c0-.549.498-.99 1.117-.99h13.373L9.285 2.62c-.456-.383-.465-1.022-.018-1.413z" fill="#FFF"></path>
    </svg>
  </span>
</a>

如您所见,纯文本在类属性中正确呈现,但花括号中的任何内容都不是来自 WordPress 和 Timber 的动态。

是否可以在 Twig 宏中使用花括号包裹的动态变量和函数,还是应该采用不同的方法?

标签: phphtmlwordpresstwigtimber

解决方案


从选项对象中删除引号和大括号 - 这样它就被视为一个字符串。像这样使用它

{{ cta.pill({
  class: "cta--pill cta--no-shadow", // this requires to be string so keep it as it is
  link: post.link, // this is dynamic variable - do NOT use quotes 
  title: __('View all services', 'howellsexcavating'),
  text: post.meta( 'module_more_button_text' )
}) }}

推荐阅读