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

如何将含capture的Liquid模板解析为Python字典(非正则)

解析Liquid Capture标签为Python字典的非正则方法

下面是几种无需正则表达式的可行方案:

  • 使用liquid-parser库解析AST
    这个Python库专门用于解析Liquid模板并生成抽象语法树(AST),你可以遍历AST节点识别并提取capture标签的信息:

    from liquid_parser import LiquidParser
    
    # 示例Liquid模板
    template = """
    {% capture product_title %}Awesome T-Shirt{% endcapture %}
    {% capture product_desc %}100% cotton, premium quality{% endcapture %}
    """
    
    parser = LiquidParser()
    ast = parser.parse(template)
    
    capture_data = {}
    # 遍历AST子节点
    for node in ast.children:
        if node.type == "Capture":
            # 提取变量名
            var_name = node.name.value
            # 提取捕获的内容(根据节点结构处理文本节点)
            content = ""
            for child in node.children:
                if hasattr(child, "value"):
                    content += child.value
            capture_data[var_name] = content
    
    print(capture_data)
    # 输出: {'product_title': 'Awesome T-Shirt', 'product_desc': '100% cotton, premium quality'}
    
  • 借助Jinja2解析器兼容处理
    Liquid和Jinja2语法高度相似,可先将Liquid的{% capture %}标签转换为Jinja2的{% set %}语法(仅针对文本捕获场景),再用Jinja2的AST解析能力提取变量:

    from jinja2 import Environment, nodes
    from jinja2.parser import Parser
    
    # 转换Liquid捕获标签为Jinja2格式
    liquid_template = """{% capture var1 %}示例内容1{% endcapture %}"""
    jinja_template = liquid_template.replace("{% capture", "{% set").replace("{% endcapture %}", "%}")
    
    env = Environment()
    parser = Parser(env, jinja_template)
    ast = parser.parse()
    
    capture_data = {}
    for stmt in ast.body:
        if isinstance(stmt, nodes.Assign):
            var_name = stmt.target.name
            content = stmt.node.value
            capture_data[var_name] = content
    
    print(capture_data)
    # 输出: {'var1': '示例内容1'}
    
  • 自定义解析器(基于PLY)
    若现有库无法满足需求,可使用PLY(Python Lex-Yacc)自定义Liquid语法的词法和语法分析器,生成AST后提取capture标签信息。这种方法需要编写语法规则,但完全可控,避免正则的局限性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 21:32:22