我已将Jinja2集成到TurboGears 2.3.12中,并在模板文件中使用了以下代码

<input type='text' value='{{ obj.attr }}' />


由于对象是新对象,因此在文本框中没有任何内容。我想将None删除为一个空字符串。找到以下解决方案
1。

<input type='text' value='{{ obj.attr or '' }}' />



2. https://stackoverflow.com/a/17661969/2102143

我想将第二个解决方案集成到TurboGears中,因为它将对整个应用程序可用,并且还可以避免使用或''

最佳答案

我已经覆盖了tg.renderers.jinja.JinjaRenderer的类方法“创建”

config / Jinja.py

try:
    import jinja2
except ImportError:  # pragma: no cover
    jinja2 = None

if jinja2 is not None:
    from jinja2.loaders import FileSystemLoader
    from jinja2 import ChoiceLoader, Environment
    from jinja2.filters import FILTERS
    from jinja2.exceptions import TemplateNotFound
else:  # pragma: no cover
    class FileSystemLoader(object):
        pass

from tg.renderers.base import RendererFactory
from tg.renderers.jinja import JinjaRenderer as jr
from tg.renderers.jinja import DottedTemplateLoader
from tg.i18n import ugettext, ungettext

class JinjaRenderer(jr):
    @classmethod
    def create(cls, config, app_globals):
        """Setup a renderer and loader for Jinja2 templates."""
        if jinja2 is None:  # pragma: no cover
            return None

        if config.get('use_dotted_templatenames', True):
            TemplateLoader = DottedTemplateLoader
            template_loader_args = {'dotted_finder': app_globals.dotted_filename_finder}
        else:
            TemplateLoader = FileSystemLoader
            template_loader_args = {}

        if not 'jinja_extensions' in config:
            config['jinja_extensions'] = []

        # Add i18n extension by default
        if not "jinja2.ext.i18n" in config['jinja_extensions']:
            config['jinja_extensions'].append("jinja2.ext.i18n")

        if not 'jinja_filters' in config:
            config['jinja_filters'] = {}

        loader = ChoiceLoader(
            [TemplateLoader(path, **template_loader_args) for path in config['paths']['templates']])

        def my_finalize(thing):
            return thing if thing is not None else ''

        jinja2_env = Environment(loader=loader, autoescape=True, finalize=my_finalize,
                                 auto_reload=config['auto_reload_templates'],
                                 extensions=config['jinja_extensions'])

        # Try to load custom filters module under app_package.lib.templatetools
        try:
            if not config['package_name']:
                raise AttributeError()

            filter_package = config['package_name'] + ".lib.templatetools"
            autoload_lib = __import__(filter_package, {}, {}, ['jinja_filters'])
            try:
                autoload_filters = dict(
                    map(lambda x: (x, autoload_lib.jinja_filters.__dict__[x]),
                        autoload_lib.jinja_filters.__all__)
                )
            except AttributeError:  # pragma: no cover
                autoload_filters = dict(
                    filter(lambda x: callable(x[1]),
                           autoload_lib.jinja_filters.__dict__.iteritems())
                )
        except (ImportError, AttributeError):
            autoload_filters = {}

        # Add jinja filters
        filters = dict(FILTERS, **autoload_filters)
        filters.update(config['jinja_filters'])
        jinja2_env.filters = filters

        # Jinja's unable to request c's attributes without strict_c
        config['tg.strict_tmpl_context'] = True

        # Add gettext functions to the jinja environment
        jinja2_env.install_gettext_callables(ugettext, ungettext)

        return {'jinja': cls(jinja2_env)}


然后在config / app_cfg.py中

from Jinja import JinjaRenderer
base_config.register_rendering_engine(JinjaRenderer)


修改后的代码

def my_finalize(thing):
            return thing if thing is not None else ''

jinja2_env = Environment(loader=loader, autoescape=True, finalize=my_finalize,
                                 auto_reload=config['auto_reload_templates'],
                                 extensions=config['jinja_extensions'])

关于python - 使用Environment.finalize在TurboGears中禁止Jinja2中的“无”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52381909/

10-11 12:40