如何解决如何在 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>
如您所见,纯文本在 class 属性中正确呈现,但花括号中的任何来自 wordpress 和 Timber 的动态内容都不是。
是否可以在 Twig 宏中使用花括号包裹的动态变量和函数,或者我应该采取不同的方法?
解决方法
从选项对象中删除引号和大括号 - 这样它就被视为一个字符串。像这样使用
{{ 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' )
}) }}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。