【问题标题】:Django parsing templates to extract variablesDjango解析模板提取变量
【发布时间】:2015-10-05 15:04:42
【问题描述】:

情况:

我正在使用 Django 模板编写自定义平面文件,但我希望能够使用相同的 django 模板来提取由 Django 模板生成的任何数据。

这是模板文件 test.conf 的示例。

object User "{{ user }}" {

  display_name = "{{first_name}} {{last_name}}"
  groups = [ "{{ group_name }}" ]
  email = "{{ email }}" }

这是生成的输出。

object User "test1" {
  display_name = "test2"
  groups = [ "test3" ]
  email = "test4" }

我希望能够使用“test.conf”Django 模板从平面文件中提取数据“test1、test2、test3、test4”。这可能吗,还是我需要使用 re 解析这些数据?

编辑:此代码 sn-p 有效。如果您使用 open("file", 'r') 打开模板文件,它会将转义码添加到字符串中。您只需要为 [. 添加 \\[ 之类的正则表达式转义标志。谢谢你的帮助。

【问题讨论】:

    标签: python django templates


    【解决方案1】:

    据我所知,没有反向解析 API,所以我认为您的想法是不可能的。

    但是,您仍然可以使用模板生成正则表达式,通过执行以下操作来提取关键字:

    from django.template import Template, Context
    import re
    
    template_source = """
    object User "{{ user }}" {
    
    display_name = "{{first_name}} {{last_name}}"
    groups = [ "{{ group_name }}" ]
    email = "{{ email }}" }
    """
    
    # re.escape will add backslashes to all non-alphanumeric characters
    template_source = re.escape(template_source)
    # but we need to fix all escaped {{ and }} characters
    template_source = template_source.replace('\{\{', '{{')
    template_source = template_source.replace('\}\}', '{{')
    
    # (you will also need to do this for the tag delimiters {% %} and for
    # any symbols inside your template tags)
    
    t = Template(template_source)
    c = Context({
        "user": "(?P<user>.*?)",
        "first_name" :"(?P<first_name>.*?)",
        # (there's probably an easier way to do this for all the parameters)
        ...
    })
    
    regex_string = t.render(c)
    
    # regex_string will look like this:
    # (actually way uglier since re.escape will also escape whitespace!)
    """
    object User \"(?P<user>.*?)\" \{
    
    display_name \= \"(?P<first_name.*?) (?P<last_name.*?)\"
    groups \= ...
    """
    
    regex = re.compile(regex_string, re.MULTILINE)
    

    【讨论】:

    • 非常聪明的解决方案!
    • 您的意思是 template_source 而不是 template.source 用于修复 {{}}
    猜你喜欢
    • 1970-01-01
    • 2012-09-30
    • 2017-04-16
    • 2013-06-14
    • 2013-02-28
    • 2011-07-04
    • 2017-09-14
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多