V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
Livid
268.79D
569.24D
V2EX  ›  Python

关于 Jinja2 模版引擎的参数传递

  •  
  •   Livid ·
    PRO
    · Mar 28, 2011 · 6282 views
    This topic created in 5516 days ago, the information mentioned may be changed or developed.
    有一些变量,在每次模版渲染的时候都会用到。

    但是 Jinja2 的 template.render() 接受的是变长参数,是否有什么办法可以在 template.render() 外面再加一层,从而每次自动传入一些必要参数呢?
    5 replies    1970-01-01 08:00:00 +08:00
    Livid
        1
    Livid  
    MOD
    OP
    PRO
       Mar 28, 2011
    OK,解决了。

    template.render() 支持两种方式传参:

    template.render(foo='bar')

    或:

    template.render({'foo' : 'bar'})

    但是不能混用,比如下面这样是不行的:

    template.render(foo='a', {'bar' : 'b'})
    lepture
        2
    lepture  
       Mar 28, 2011
    这样的思路不知可否?


    from jinja2 import Environment, FileSystemLoader

    class render_jinja:
    """
    modified from web.contrib.template
    """
    def __init__(self, *arg, **kwargs):
    extensions = kwargs.pop('extensions',[])
    filters = kwargs.pop('filters', {})
    gvars = kwargs.pop('gvars', {}) # global vars

    self._lookup = Environment(loader=FileSystemLoader(*arg, **kwargs), extensions=extensions)
    self._lookup.globals.update(gvars)
    self._lookup.filters.update(filters)

    def render_template(self, name, **kwargs):
    t = self._lookup.get_template(name)
    return t.render(**kwargs)


    然后给定值到gvars
    Livid
        3
    Livid  
    MOD
    OP
    PRO
       Mar 28, 2011
    @lepture 感谢 :)

    主要是希望传递一些每次都会用到的值,比如当前用户,当前域名和图片服务器域名等等。

    目前通过改动 BaseHandler 包装了一切的龌龊。XD
    lepture
        4
    lepture  
       Mar 29, 2011
    悲剧,在打字的时候 @Livid 已经解决了。
    fanzeyi
        5
    fanzeyi  
       Mar 29, 2011
    我习惯性的弄个字典类型…………
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1006 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 18:06 · PVG 02:06 · LAX 11:06 · JFK 14:06
    ♥ Do have faith in what you're doing.