因此,我有几个jinja2模板,它们通过python脚本执行,并分别生成不同的输出文本。每个输出文本都有固定的模板值和一些可变值。我需要创建一个javascript函数来识别输出纯文本中哪些是变量(以便突出显示它们)以及哪些是固定文本。我可以访问模板文件,所以我最初尝试使用regex查找所有大括号,并在这些位置,在输出文本中,开始高亮显示。这很好,直到我遇到if和for语句,我的函数失败。以下是文件示例:
template_exp.jinja2(这是一个示例,我有许多具有各种结构的模板)
something fixed {{ a variable }}
something else fixed
{% if sth happens %}
text {{variable}} text
{% elif another condition %}
text text {{variable}}
{% else %}
{{variable}} text text
{% endif %}
{% for element in array %}
something {{element}}
{% endfor %}
app.py(这是一个 flask 应用程序)
def index()
template_name='template_example.jinja2'
templates_folder='./templates/'
output_text=function(template_name)
with open(templates_path+template_name, 'r', newline="") as file:
template_text=file.read()
return render("output.html", text=output_text, template_text=template_text)
output.html
<div class="output" id="output">
{% autoescape false %}
{{text}}
{% endautoescape %}
</div>
<div style="display: none" id="template_text">{{template_text}}</div>
<script>
function highlight_variables(template_text, output_text){
var text = output_text;
var index_end_all=template_text.length;
var regex=/{{(.*?)}}/g;
var regex2=/{%(.*?)%}/g;
var cantidad=0;
var matches= [... template_text.matchAll(regex)]
var index_ant=0;
matches.forEach((m)=>{
index_end_all+=cantidad*31 //31 characters are the ones added with the span with class highlight
var fixed_text = template_text.substring(index_ant,m.index + cantidad*31);
var matches2=[... fixed_text.matchAll(regex2)]
matches2.forEach((m2)=>{
if (m2[1].indexOf('if')){
//what to do if is an if statement
//var st = fixed_text.substring(m2.index,m2[0].length+4)
fixed_text = fixed_text.substring(m2[0].length+5)// wrong
} else{
//what to do if is a for statement
}
})
fixed_text=fixed_text.replace('\n','<br>')
var index_start = text.indexOf(fixed_text) + fixed_text.length;
var aux = text.substring(index_start)
var aux2= template_text.substring(index_ant)
if(aux2.indexOf('\n')<aux2.indexOf('{{')){
//skips other variables in the same line, and highlights them in one loop;
var index_end = index_start + aux.indexOf('<br>')
text = text.substring(0,index_start) + "<span class='highlight'>" +
text.substring(index_start,index_end) + "</span>" + text.substring(index_end, index_end_all);
cantidad++;
}
index_ant=m.index+m[1].length+4; //previous index so that next loop starts looking from there
})
return text
}
var output = document.getElementById('output');
var template_text = document.getElementById('template_text').innerText;
var text= highlight_variables(template_text, output.innerHTML)
output.innerHTML=text;
</script>
暂无答案!
目前还没有任何答案,快来回答吧!