2017-01-22 69 views
0

我的jinja2模板接收可能包含任意數量不同語言的代碼塊。我想將正確的詞法分析器傳遞給模板,並使用jinja2-highlight插件(pygments)進行相應的渲染。 我使用'command'變量呈現我的模板,該變量是一個保存模板其餘部分所需的所有數據的字典。理想情況下,我想沿着這些線路jinja2中的變量詞法分析器突出顯示

{% highlight "{{ command.lexer }}", lineno='table' %}{{ command.script }}{% endhighlight %} 

我試圖做一些事情:

{% highlight command.lexer, lineno='table' %} 
{% highlight 'command.lexer', lineno='table' %} 
{% highlight '{{ command.lexer }}', lineno='table' %} 

甚至

{% set lexer = command.lexer %} 
{% highlight 'lexer', lineno='table' %} 
{% highlight '{{ lexer }}', lineno='table' %} 

我似乎無法找出渲染的組合jinja2和jinja2-highlight/pygments之間的規則。

我真的想不這樣做:

{% if command.lexer == 'bash' %} 
{% highlight 'bash', lineno='table' %} 
{% elif command.lexer == 'perl' %} 
{% highlight 'perl', lineno='table' %} 
... 
{% endif %} 

它似乎有與Jinja2的解析器類的事,但我有點卡住..感覺就像我忽視的東西不重要的。

各種錯誤消息看起來都像:

jinja2.exceptions.TemplateSyntaxError: expected token 'end of statement block', got ',' 

回答

0

不幸的是這似乎是不可能與當前的插件。沒有遞歸的jinja語法,插件解析的方式似乎不能很好地處理任何變量輸入。我所接觸的作者,沒有任何回覆和瀏覽插件的源代碼後,似乎有可能,但不值得我的時間在這一刻進行必要的修改,所以..

{% if command.lexer == 'bash' %} 
{% highlight 'bash', lineno='table' %} 
{% elif command.lexer == 'perl' %} 
{% highlight 'perl', lineno='table' %} 
... 
{% endif %} 

..它是。

0

您是否嘗試過使用自定義過濾器請參閱http://jinja.pocoo.org/docs/2.10/api/#custom-filters? (我的建議一點兒也不使用的Jinja2高亮擴展名,但只有Pygments來做

在filters.py文件(如有必要創建它)

# highlight Filter 
from pygments import highlight 
from pygments import lexers 
from pygments.formatters import HtmlFormatter 

lexers_dict = dict() 
html_formatter = HtmlFormatter() 

def do_highlight(content, language):  
    lexers_dict.setdefault(language,lexers.get_lexer_by_name(language)) 

    return highlight(content, lexers_dict[language], html_formatter) 


def init_app(app): 
    """Initialize a Flask application with custom filters."""  
    app.jinja_env.filters['light'] = do_highlight 
在模板文件

(的.html)

<div class="content">{{ command.script | light(command.lexer) | safe }}</div> 
在您的應用程序文件

(app.py):

from my_app import filters 
filters.init_app(app)