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

Symfony Twig配置:如何排除指定文件夹不生成缓存文件

仅禁用Twig指定路径模板的缓存方案

完全可以实现仅对Modules路径下的模板禁用缓存,同时保留默认模板的缓存功能,具体实现步骤如下:

1. 自定义Twig缓存策略类

创建一个缓存策略类,通过模板的命名空间判断是否禁用缓存:

// src/Twig/CustomCacheStrategy.php
namespace App\Twig;

use Twig\Cache\CacheStrategyInterface;
use Twig\TemplateWrapper;

class CustomCacheStrategy implements CacheStrategyInterface
{
    private string $defaultCacheDir;

    public function __construct(string $defaultCacheDir)
    {
        $this->defaultCacheDir = $defaultCacheDir;
    }

    public function generateKey(TemplateWrapper $template, string $name): string|false
    {
        // 匹配Modules命名空间下的所有模板
        if (str_starts_with($name, '@Modules/')) {
            return false; // 返回false直接禁用该模板的缓存
        }

        // 默认模板沿用原有缓存路径规则
        return $this->defaultCacheDir . '/' . str_replace(['/', '\\'], '_', $name) . '.php';
    }
}

2. 配置Symfony服务

将自定义缓存策略类注册为服务,传入默认Twig缓存目录:

# config/services.yaml
services:
    App\Twig\CustomCacheStrategy:
        arguments:
            $defaultCacheDir: '%kernel.cache_dir%/twig'
        tags:
            - { name: twig.cache_strategy }

3. 修改Twig配置

指定Twig使用自定义缓存策略:

# config/packages/twig.yaml
twig:
    paths:
        '%kernel.project_dir%/modules': Modules
    cache: '@App\Twig\CustomCacheStrategy'

效果说明

  • @Modules/命名空间下的模板会完全禁用缓存,每次请求都会重新编译模板,FTP更新后立即生效
  • 默认路径(如app/templates/)的模板仍正常使用缓存,不会影响系统性能
  • 无需手动清理Symfony缓存,维护人员更新模板后无需联系开发人员

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 21:20:27