【问题标题】:flask render_template not working with anchor tag # - jinja2.exceptions.TemplateNotFound烧瓶渲染模板不使用锚标记# - jinja2.exceptions.TemplateNotFound
【发布时间】:2014-11-06 02:15:46
【问题描述】:

在 url_for 方法中,您可以传入一个 _anchor 参数来在页面加载时加载锚标记。

我将如何使用 render_template 做同样的事情?

我可以

render_template('profile/index.html') 

没有任何问题,但是当我在 html 末尾添加锚标记并尝试这样做时

render_template('profile/index.html#h1")

我收到模板未找到错误

jinja2.exceptions.TemplateNotFound
TemplateNotFound: profile/index.html#h1

【问题讨论】:

  • 你想完成什么? render_templateurl_for 做两件非常不同的事情。 render_template 采用要加载的模板文件的名称。 # 在此上下文中没有特殊含义。
  • 感谢 Dim 抽出时间来帮助我。可能是我在这里没有以正确的方式思考它。我有一个包含 3 个选项卡的页面,其中一个选项卡中有一个表单。当我提交表单时,我会处理它并希望在打开相同的选项卡的情况下返回页面。如果我进行 URL 重定向,我可以加载表单选项卡,但我会丢失表单值条目。将表单条目设置为会话并将它们拉回将是一个解决方案,但似乎有点粗糙?
  • 解决这个问题的一个好方法是你可以用 WT-Forms 做些什么,比如 populate_obj。而 render_template 只会接受模板的文件名,与链接有关的任何内容都应该转到 url_for
  • 您可能只想向模板传递一个值,以指示要呈现哪个选项卡。 render_template('profile/index.html', active_tab='...')

标签: flask anchor template-engine jinja2


【解决方案1】:

基本上这就是我最终所做的,我在 render_template 中传入了一个值

return render_template('profile/index.html', set_tab=1)

在javascript的客户端,我做了以下设置标签

<script>
   var obj_load={% if set_tab==1%}1{%else%}0{%endif%};
   tab_load=(obj_load?"#h1":"#");

   $(document).ready(function () {
       if(location.hash || obj_load) {
       $('a[href=' + (location.hash ||  tab_load) + ']').tab('show');
       }
    });

</script>

fyi,我正在使用 bootstrap 3 的选项卡窗格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2018-06-09
    • 1970-01-01
    相关资源
    最近更新 更多