You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WordPress切换Timber至Composer版遇Twig扩展重复注册错误

解决Timber从插件版切换到Composer依赖版后StringLoaderExtension重复注册错误

问题分析

切换到Composer依赖版Timber后,前端渲染页面时抛出LogicException: Unable to register extension "Twig\Extension\StringLoaderExtension" as it is already registered错误,核心原因是Composer版Timber已默认内置并自动注册了StringLoaderExtension,而你在DLDSite类的add_to_twig方法中又手动重复添加了该扩展,导致注册冲突。插件版Timber未默认注册此扩展,因此之前无报错。

解决方案

1. 移除手动重复注册的代码

直接删除add_to_twig方法中添加StringLoaderExtension的代码行即可:

修改前的add_to_twig方法:

public function add_to_twig($twig) {
    $twig->addExtension( new Twig\Extension\StringLoaderExtension() );
    $twig->addFilter(new Twig_SimpleFilter('remove_suggestion_and_loop', array( $this, 'remove_suggestion_and_loop' )));
    // 其他过滤器代码...
    return $twig;
}

修改后的add_to_twig方法:

public function add_to_twig($twig) {
    $twig->addFilter(new Twig_SimpleFilter('remove_suggestion_and_loop', array( $this, 'remove_suggestion_and_loop' )));
    $twig->addFilter(new Twig_SimpleFilter('remove_suggestion_and_loop_autoplay', array( $this, 'remove_suggestion_and_loop_autoplay' )));
    $twig->addFilter(new Twig_SimpleFilter('remove_suggestion_and_loop_autoplay_popup', array( $this, 'remove_suggestion_and_loop_autoplay_popup' )));
    $twig->addFilter(new Twig_SimpleFilter('embed_video_all_params', array( $this, 'embed_video_all_params' )));
    $twig->addFilter(new Twig_SimpleFilter('shuffle', array( $this, 'shuffle' )));
    return $twig;
}

2. 排查其他潜在重复注册点

检查主题其他代码片段或已激活插件(如WPML、ACF等是否包含Twig扩展逻辑),确保没有其他地方重复注册StringLoaderExtension。

3. 确认Composer依赖版本一致性

执行composer update命令,确保Timber及其依赖(包括Twig)的版本为最新且无冲突,避免版本差异导致的扩展注册逻辑异常。

额外说明

如果需要使用StringLoaderExtension的功能(比如{% include_string %}标签),Composer版Timber已默认提供支持,无需手动添加即可直接使用。

内容的提问来源于stack exchange,提问作者Axel Denhaut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 12:53:25