【问题标题】:Link to a specific location in a Flask template链接到 Flask 模板中的特定位置
【发布时间】:2016-03-07 12:23:04
【问题描述】:

在 HTML 中,我可以直接链接到页面上的特定位置,假设存在具有给定 id 的元素:

<a href="http://www.example.com/stuff.html#exactlocation">Go there</a> 

在 Flask 中,我尝试将锚点添加到 render_template,但我得到了 jinja2.exceptions.TemplateNotFound: stuff.html#exactlocation

@main.route('/exactlocation')
def exactlocation():
    return render_template('stuff.html#exactlocation')

如何链接到模板中的特定位置?

【问题讨论】:

  • 这是浏览器的行为。只需正常渲染您的模板,浏览器就会处理它(假设您在页面上有命名的锚点)。
  • @dirn 我不确定你的意思。如果我使用 return render_template('stuff.html') 浏览器如何知道转到页面上的特定位置而不是顶部,在页面加载时运行 javascript 检查?
  • 浏览器会自动跳转到命名锚点,不需要 JavaScript。唯一的要求是命名的锚点(即&lt;a name="exactlocation"&gt;&lt;/a&gt;)存在于 HTML 中。

标签: python flask jinja2


【解决方案1】:

感谢 dirn 的 cmets,我设法使用下面的代码完成了这项工作。

_anchor 关键字传递给 url_for 以将锚附加到生成的 URL。

导航菜单:

<a href="{{ url_for('.stuff', _anchor='exactlocation') }}">Go to specific id on suff page</a>

烧瓶路线:

@main.route('/')
def stuff():
    return render_template('stuff.html')

stuff.html:

...
<section id="exactlocation">
...

【讨论】:

  • 这也是动态的,例如:&lt;a href=" {{ url_for('comments', _anchor=comment.id) }}"&gt;
猜你喜欢
  • 1970-01-01
  • 2014-07-14
  • 2018-09-23
  • 2014-02-17
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多