2015-10-05 86 views
4

現狀:Django的分析模板提取變量

我使用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」。這是可能的,還是我需要解析這些數據?

編輯:此代碼段工作。如果打開模板文件(「文件」,「r」),它會將轉義碼添加到字符串中。您只需要添加正則表達式轉義標誌,如\\ [for [。感謝您的幫助。

回答

4

據我所知,沒有反向解析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) 
+0

真的聰明的解決方案! – Tiago

+1

你是不是指'template_source'而不是'template.source'來修復'{{'和'}}'? – developius

+0

@developius修好了,謝謝! – gbs