如何动态选择要在flask中使用的模板目录? [英] How to dynamically select template directory to be used in flask?

查看:26
本文介绍了如何动态选择要在flask中使用的模板目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,flask 使用存储在模板"目录中的模板文件:

By default flask uses template files stored in "template" directory :

/flaskapp
    /application.py
    /templates
        /hello.html

有没有办法根据登录的用户动态选择模板目录?这就是我想要的目录结构:

Is there any way to dynamically choose template directory according to user logged in? This is how I want the directory structure to be :

/flaskapp
    /application.py
    /templates (default template goes here)
        /hello.html
    /userdata
        /user1
            /template1
                 hello.html
            /template2
                 hello.html
        /user2
            /template1
                 hello.html
            /template2
                 hello.html

现在如果我有登录用户的用户名和用户激活的模板名称,是否可以动态选择加载模板文件的目录?例如,

Now if I have the username of logged in user and the name of template activated by user, is it possible to dynamically select the directory to load template files? For example,

/userdata/<username>/<activated template name>/

代替固定

/templates/

我试图为我的 Web 应用程序实现类似 wordpress 的主题系统,用户可以在其中为他的网站上传/选择主题.

What I am trying to achieve is a wordpress like theme system for my web application where users can upload/select themes for his website.

推荐答案

还可以覆盖 Jinja 加载器并设置 Jinja 将在其中查找模板的路径.喜欢:

There is also the possibility to overwrite Jinja loader and set the paths where Jinja will look for the templates. Like:

my_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(['/flaskapp/userdata', 
                                 '/flaskapp/templates']),
    ])
app.jinja_loader = my_loader

目录按照 Jinja 需要首先开始查找的顺序排列.然后从视图中,您可以像这样呈现用户特定的模板:

Directories are arranged in the order where Jinja needs to first start looking for it. Then from the view you can render user specific template like this:

render_template('%s/template1/hello.html' % username)

您可以在视图中动态更改用户名的位置.当然,您也可以选择要渲染的模板(1 或 2).但基本上你真正想念的是这个带有自定义路径的自定义 Jinja 加载器.

where username you can dinamically change in the view. Of course you can also there choose which template (1 or 2) to render. But basically what you really miss is this custom Jinja loader with the custom paths.

希望有所帮助或提供想法:)

Hope that helped or gave the ideas :)

这篇关于如何动态选择要在flask中使用的模板目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆