#!/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)
因为没有人回答这个问题,我找到了答案
这将产生未声明变量的列表,因为这不是在运行时执行的,它将产生所有变量的列表。
注意:这将生成使用
include
和extends
包含的html文件。我也有同样的需求,我已经编写了一个名为jinja2schema的工具。它提供了一个从Jinja2模板推断类型的启发式算法,还可以用于获取所有模板变量的列表,包括嵌套的变量。
下面是一个简单的例子:
对于我的鹈鹕主题,我创建了一个工具来分析我的模板文件中的所有jinja变量。
我共享我的代码
此脚本从模板文件中存在的所有变量生成一个示例配置,并从我的官方pelicanconf.py获取一个变量
从模板文件中提取所有变量的函数
完整的剧本
这个程序的示例结果
有关此脚本的更多详细信息,请参见https://github.com/badele/pelican-theme-jesuislibre
相关问题 更多 >
编程相关推荐