使用Timber时ACF区块无法显示,请求排查问题
排查ACF+Timber区块无法显示的问题
结合你提供的代码,以下是几个核心错误点和排查方向:
1. 确认ACF字段组已关联目标区块
你的Twig模板调用了fields.title、fields.description等字段,但如果未在ACF后台创建对应字段组,并将字段组关联到slug为example_block的「Example Block」区块,get_fields()会返回空值,导致区块无内容显示。
操作步骤:
- 进入ACF后台「字段组」页面
- 创建/编辑字段组,在「位置」规则中选择「区块」→「等于」→「Example Block」
- 确保字段的slug与模板中调用的名称完全一致(如
title、description)
2. 检查Twig模板路径是否符合Timber规则
Timber::render('block/example-block.twig', $context)的路径需匹配Timber的模板查找逻辑:
- 默认Timber会在主题根目录的
templates文件夹下查找模板 - 若模板放在
your-theme/templates/block/example-block.twig,路径正确;若放在your-theme/block/example-block.twig,需修改路径为'/block/example-block.twig',或通过Timber::$dirname = array('templates', 'block')添加额外查找目录
3. 修复CSS选择器不匹配问题
模板中容器ID是example-{{ block.id }},但内嵌CSS的选择器是#testimonial-{{ block.id }},两者不匹配会导致样式失效,修改为:
<style type="text/css"> #example-{{ block.id }} { background: {{ fields.background_color }}; color: {{ fields.text_color }}; } </style>
4. 修正PHP代码中的语法错误
你的functions.php注释里的doesn’t使用了中文单引号(’),这会触发PHP语法错误,导致my_acf_init函数无法执行、区块注册失败,替换为英文单引号:
// Bail out if function doesn't exist.
同时确认主题已正确初始化Timber:
- 通过Composer安装Timber后,在
functions.php顶部添加:require_once get_template_directory() . '/vendor/autoload.php';
5. 调试变量确认数据传递状态
在Twig模板中添加调试代码,查看block和fields是否有数据:
{% if is_preview %} <p>I will only appear in the editor.</p> <pre>{{ block|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre> <pre>{{ fields|json_encode(constant('JSON_PRETTY_PRINT')) }}</pre> {% endif %}
若编辑器中无调试内容,需查看PHP错误日志,排查Timber或ACF相关报错。
内容的提问来源于stack exchange,提问作者Alex McIver
相关产品推荐
相关产品推荐

