Django解析模板以提取变量

Sco*_*ttE 4 python django templates

情况:

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

以下是模板文件test.conf的示例.

object User "{{ user }}" {

  display_name = "{{first_name}} {{last_name}}"
  groups = [ "{{ group_name }}" ]
  email = "{{ email }}" }
Run Code Online (Sandbox Code Playgroud)

这是生成的输出.

object User "test1" {
  display_name = "test2"
  groups = [ "test3" ]
  email = "test4" }
Run Code Online (Sandbox Code Playgroud)

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

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

gbs*_*gbs 5

据我所知,没有反向解析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)
Run Code Online (Sandbox Code Playgroud)