jinja2扩展,允许将任何筛选器用作自定义autescape筛选器。

jinja2-ext-custom-autoescaping的Python项目详细描述


概述

Jinja2扩展,允许将任何筛选器用作自定义的Autoscape筛选器。

此包允许您定义规则以确定自定义自动转义筛选器将在何时 使用已用于确定的“选择自动转义”方法启用 启用内置自动转义筛选器时。

用法

from jinja2_ext_custom_autoescaping import CustomAutoescapeExtension, enable_custom_autoescaping
from jinja2 import Environment, select_autoescape, FileSystemLoader

# Your custom filter...        
def my_filter(val):
    print(val)
    if isinstance(val, str):
        return val.replace(r"\\", r"\\\\")
    return val

    
# Here you set the rules for when the built-in autoescaping will be enabled
built_in_select_autoescape = select_autoescape(enabled_extensions=['html', 'htm', 'xml'],
                                               disabled_extensions=['txt', 'tex'],
                                               default_for_string=True,
                                               default=True)

# - select_autoescape is a closure
# - enabled_extensions takes precedence over disabled_extensions, so an extension in both lists will be enabled
# - You most likely do not want to have custom autoescaping on while built-in autoescaping is also on

# Here you set the rules for when your custom autoescaping will be enabled
custom_select_autoescape = select_autoescape(enabled_extensions=['tex', 'txt'],
                                             disabled_extensions=[],
                                             default_for_string=False,
                                             default=False)

# Just focusing on the important parts of your Environment construction.
env = Environment(extensions=[CustomAutoescapeExtension],
                  loader=FileSystemLoader(['.']),
                  autoescape=built_in_select_autoescape)

opts = {'custom_select_autoescape': custom_select_autoescape,
        'custom_autoescape_filter_name': 'my_filter',
        'custom_autoescape_filter_func': my_filter}

# Register the filter and enables autoescaping
enable_custom_autoescaping(env, **opts)

# Now you are ready to go...
template = env.get_template('test_template.txt')
print(template.render(var={'entry 1': 'value 1', 'entry2': r'val\\ue 2'}))

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
junit cucumber为什么会找到“runTest.java”来运行测试?   在Eclipse中找不到java KeyPairGenerator   java NotSerializableException即使在实现Serializable之后   noclassdeffounderror(java字符串连接)为什么会出现这种异常?   java Guice:将接口绑定到由动态代理创建的实例   使用Spring数据neo4j创建空间索引时发生java错误   java对于需要在50多个excel文件上运行并且每个文件平均包含25k行的项目,最佳的方法是什么   javaNIO中的java缓冲区写入/发送消息问题   如何在Java/eclipse中添加不调用super()的警告   JavaSpring:mvcUrl映射错误的id   java应该在getInstance或构造函数中使用Init方法吗?   安卓中的java空指针异常错误   java Jsoup不能完全获取原始html代码