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

如何强制项目为特定标签自动包裹{% raw %}与{% endraw %}?

解决方案:自动为Cookiecutter模板中的Jinja标签添加Raw包裹

针对在特定子文件夹的.html文件中自动包裹{% ... %}标签的需求,提供三种可行方案:

1. 编辑器正则批量替换(小项目快速处理)

直接用编辑器的全局查找替换功能,限定目标文件夹和.html文件类型:

  • 查找正则:{%(.*?)%}
  • 替换内容:{% raw %}{%$1%}{% endraw %}
    注:VS Code、PyCharm等编辑器都支持带正则的批量替换,记得勾选正则匹配选项

2. Cookiecutter钩子脚本(自动化推荐方案)

通过Cookiecutter的post-gen-project钩子,在项目生成完成后自动处理文件:

  1. 在你的Cookiecutter模板根目录下创建hooks文件夹,新建post-gen-project.py文件
  2. 写入以下代码(根据你的目标文件夹调整TARGET_DIR):
import os
import re

# 替换为你需要处理的子文件夹路径(比如项目生成后的templates目录)
TARGET_DIR = os.path.join(os.getcwd(), "templates")
# 匹配Jinja标签的正则,排除已被raw包裹的内容
JINJA_TAG_REGEX = re.compile(r'(?<!{% raw %}){%(.*?)%}(?!{% endraw %})', re.DOTALL)

def process_html_file(file_path):
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    # 替换所有符合条件的Jinja标签
    updated_content = JINJA_TAG_REGEX.sub(r'{% raw %}{%\1%}{% endraw %}', content)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(updated_content)

def main():
    # 遍历目标文件夹下所有.html文件
    for root, _, files in os.walk(TARGET_DIR):
        for filename in files:
            if filename.endswith('.html'):
                process_html_file(os.path.join(root, filename))

if __name__ == "__main__":
    main()

这个脚本会在用户生成项目后自动执行,批量处理指定目录下的所有.html文件,自动为未被raw包裹的{% ... %}标签添加{% raw %}和{% endraw %}包裹。

3. 模板文件手动预处理(单个文件场景)

如果仅需处理少数几个.html模板文件,可直接在模板中手动用{% raw %}包裹需要保留的Jinja标签,但这种方式适合小范围场景,自动化程度低。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:21:35