2011-11-24 43 views
22

我想要獲取模板中所有變量和塊的列表。我不想創建我自己的解析器來查找變量。我嘗試使用以下代碼片段。如何獲取jinja 2模板中所有變量的列表

from jinja2 import Environment, PackageLoader 
env = Environment(loader=PackageLoader('gummi', 'templates')) 
template = env.get_template('chat.html') 

template.blocks是字典鍵進行塊,我怎麼能得到塊內的所有變量?

回答

38

因爲沒有人回答了這個問題,我找到了答案

from jinja2 import Environment, PackageLoader, meta 
env = Environment(loader=PackageLoader('gummi', 'templates')) 
template_source = env.loader.get_source(env, 'page_content.html')[0] 
parsed_content = env.parse(template_source) 
meta.find_undeclared_variables(parsed_content) 

,因爲這不是在運行時執行這將產生未聲明的變量列表,它會產生的所有變量的列表。

注意:這將生成使用includeextends包含的html文件。

+0

+1 - 感謝張貼答案! –

+1

歡迎:),我想答案可以幫助一些。 – Kracekumar

+5

不幸的是,沒有拿起變量的屬性(即{{something.nested}}提供set(['something']) – Bemis

4

對於我的鵜鶘主題,我創建了一個工具來分析我的模板文件中的所有jinja變量。

我分享我的代碼

這個腳本生成的所有變量示例配置模板文件中存在,並且從我的官方pelicanconf.py

是提取所有變量從模板文件中的函數得到變量

def get_variables(filename): 
    env = Environment(loader=FileSystemLoader('templates')) 
    template_source = env.loader.get_source(env, filename)[0] 
    parsed_content = env.parse(template_source) 

完整的腳本

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
# 
# use: 
# generate_pelicanconf-sample.py my_official_blog/pelicanconf.py 

import sys 
import imp 
import os 

from jinja2 import Environment, FileSystemLoader, meta 


# Search all template files 
def list_html_templates(): 
    dirList = os.listdir('templates') 

    return dirList 


# get all variable in template file 
def get_variables(filename): 
    env = Environment(loader=FileSystemLoader('templates')) 
    template_source = env.loader.get_source(env, filename)[0] 
    parsed_content = env.parse(template_source) 

    return meta.find_undeclared_variables(parsed_content) 


# Check if the pelicanconf.py is in param 
if len(sys.argv) != 2: 
    print("Please indicate the pelicanconf.py file") 
    sys.exit() 

# Get all vars from templates files 
all_vars = set() 
files = list_html_templates() 
for fname in files: 
    variables = get_variables(fname) 
    for var in variables: 
     if var.isupper(): 
      all_vars.add(var) 

m = imp.load_source('pelicanconf', sys.argv[1]) 

# Show pelicanconf.py vars content 
for var in all_vars: 
    varname = 'm.%s' % var 
    if var in m.__dict__: 
     print ("%s = %s" % (var, repr(m.__dict__[var]))) 


    return meta.find_undeclared_variables(parsed_content) 

這一計劃

LINKS = ((u'Home', u'/'), (u'archives', u'/archives.html'), (u'tags', u'/tags.html'), (u'A propos', u'http://bruno.adele.im')) 
SITESUBTITLE = u'Une famille compl\xe8tement 633<' 
DEFAULT_LANG = u'fr' 
SITEURL = u'http://blog.jesuislibre.org' 
AUTHOR = u'Bruno Adel\xe9' 
SITENAME = u'Famille de geeks' 
SOCIAL = ((u'adele', u'http://adele.im'), (u'feed', u'http://feeds.feedburner.com/FamilleDeGeek'), (u'twitter', u'http://twitter.com/jesuislibre.org'), (u'google+', u'https://plus.google.com/100723270029692582967'), (u'blog', u'http://blog.jesuislibre.org'), (u'facebook', u'http://www.facebook.com/bruno.adele'), (u'flickr', u'http://www.flickr.com/photos/b_adele'), (u'linkedin', u'http://fr.linkedin.com/in/brunoadele')) 
FEED_DOMAIN = u'http://blog.jesuislibre.org' 
FEED_ALL_ATOM = u'feed.atom' 
DISQUS_SITENAME = u'blogdejesuislibreorg' 
DEFAULT_PAGINATION = 10 
GITHUB_BLOG_SITE = u'https://github.com/badele/blog.jesuislibre.org' 

對於此腳本的更詳細的抽樣結果看https://github.com/badele/pelican-theme-jesuislibre

6

我有同樣的需要,我寫了一個名爲jinja2schema工具。它提供了一個用於從Jinja2模板中推斷類型的啓發式算法,也可以用於獲取所有模板變量(包括嵌套變量)的列表。

這裏是這樣做的一個簡單的例子:

>>> import jinja2 
>>> import jinja2schema 
>>> 
>>> template = ''' 
... {{ x }} 
... {% for y in ys %} 
...  {{ y.nested_field_1 }} 
...  {{ y.nested_field_2 }} 
... {% endfor %} 
... ''' 
>>> variables = jinja2schema.infer(template) 
>>> 
>>> variables 
{'x': <scalar>, 
'ys': [{'nested_field_1': <scalar>, 'nested_field_2': <scalar>}]} 
>>> 
>>> variables.keys() 
['x', 'ys'] 
>>> variables['ys'].item.keys() 
['nested_field_2', 'nested_field_1'] 
1

解決方案: https://gist.github.com/sxslex/822bd2405885294747b86aac187f1aa8

def template(html, **params): 
    import jinja2 
    env = jinja2.Environment(loader=FileSystemLoader('')) 

    def tojson(s):          
     import json 
     return json.dumps(s) 
    env.filters['tojson'] = tojson 
    template = env.from_string(html) 
    return template.render(context=params, **params) 

print(template('{{ context|tojson }}', name='slex', value=39)) 
+0

github鏈接不工作 – HDJEMAI

相關問題