在元素 acf 字段或对象中连接

问题描述

我正在尝试连接一个 Twig 变量和一个 ACF 选项字段,但它不起作用。

我有两个页脚,我想根据正确的页面选择正确的页脚。

{% if post.slug == "page1" %}
    {% set pageType = "pages" %}
{% elseif post.slug == "page2" %}
    {% set pageType = "otherspages" %}
{% endif %}

<footer id="footer">
   <h2>{{ options.footer_~pageType~_titre }}</h2>
   <div>{{ options.footer_~pageType~_container }}<div>
</div>

ACF 字段被称为 footer_page_titre 或 footer_otherpage_titre,具体取决于我要显示的页脚

谢谢

解决方法

首先尝试构造字段名称,例如使用 twig 格式过滤器,它通过替换占位符来格式化给定的字符串,类似于 sprintf,然后在选项数据数组中访问字段值。

构造字段名称:

{% set footer_title = "footer_%s_title"|format(pageType) %}

通过数组键访问值

<h2>{{ options[footer_title] }}</h2>