V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
amxku
V2EX  ›  Python

请教个Jinja2变量传递的问题

  •  
  •   amxku · 2012-10-16 23:51:54 +08:00 · 3518 次点击
    这是一个创建于 4215 天前的主题,其中的信息可能已经有所发展或是发生改变。
    Jinja2中,我们在加载模版的过程大概是这样的:

    countent = self.render_template('home.html',title=u'测试',item=item,item1=item1,item2=item2,item3=item3,item4=item4)

    每次都要写一堆item=item

    没有一个什么配置或是别的什么,可以一次搞定的,不用每个页面都写一堆等于什么等于什么

    我记得Django里面是有个的,Jinja2中哦给你不知道要怎么处理了,请教了,谢谢
    5 条回复    1970-01-01 08:00:00 +08:00
    fanzeyi
        1
    fanzeyi  
       2012-10-16 23:58:59 +08:00
    self.render_template('home.html', **locals())
    laiwei
        2
    laiwei  
       2012-10-17 00:33:53 +08:00
    配合楼上的方法


    然后,把一些大多数模板页面都会用到的变量,存为g的一个属性

    在模板中可以引用了
    tioover
        3
    tioover  
       2012-10-17 19:52:50 +08:00   ❤️ 1
    def render(*args, **kwargs):
    。。return self.render_template(自动传入的那些, *args, **kwargs)
    zhy0216
        4
    zhy0216  
       2012-11-29 00:02:12 +08:00
    如果是一直用的变量, 可以注入. 官方代码:
    @app.context_processor
    def inject_user():
    return dict(user=g.user)
    bindiry
        5
    bindiry  
       2013-01-07 17:30:44 +08:00
    @laiwei 如果我用的是tornado+jinja2,请问 g 怎么调用?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   849 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:42 · PVG 06:42 · LAX 15:42 · JFK 18:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.