php - 如何在 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 宏中使用花括号包裹的动态变量和函数,还是应该采用不同的方法?
解决方案
从选项对象中删除引号和大括号 - 这样它就被视为一个字符串。像这样使用它
{{ 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' )
}) }}
推荐阅读
- javascript - 如何使用加载的 SVG 模块
- android - 为什么“beeware create android”对我不起作用?
- javascript - 具体化框架中的下拉菜单
- winapi - 处理 ON_WM_NCPAINT() 消息和 OnNCPaint() 覆盖的问题。(覆盖默认 MFC 窗口边框)[2020]
- javascript - 反应在新项目中显示的旧 Favicon
- android - 在 Android 上中断动画导航会导致空白屏幕
- python - 在python中检查考试
- python - 是什么导致我下载的文件不真实?
- c# - 在 ASP .NET Core 3.1、WebAPIs 中,进行 JSON 请求验证最合乎逻辑的地方是什么?
- react-native - 使用 react-native-http-bridge 在 react native 中创建 http 服务器