How to identify an anchor in a url in Django?

余生长醉 提交于 2019-11-28 02:16:43
Rob Osborne

You hit on it in your question. The anchor part of the URL is not passed to the server, it is only used client side. Why not use standard get parameters:

articles/1234?slide=5

Since you are stuck with this url format, you might want to use a animated scroll of some kind which might make this less annoying, checkout the answers to this question jquery smooth scroll to an anchor?

No browser sends the "hashtag" to the server.

one of the common ways around this is to have a javascript capture the hashtag on load/read , and call a function to initialize the page (via ajax).

Also, the common term for this is "hashbang url". If you search on that term, you'll find a lot more relevant information.

The page is jumping around, because # is used to point to page anchors in the HTML specification. http://example.com/gallery/1234#slide5 tells the browser to go to the slide5 anchor on http://example.com/gallery/1234

The anchor (bit after the #) isn't part of the bit of the URL that's matched. They are used for an anchor (i.e. link) within a page. They are generally for the benefit of the browser (so the browser can scroll to that bit of the page) not the server but people seem to be abusing them these days. It's not surprising that Django doesn't pick them up because they are not considered a useful part of the URL for the server.

Here is documentation from an older spec of HTML but it is still valid: http://www.w3.org/TR/html4/struct/links.html#h-12.2.3

How to do it:

If you want to get this in your view, look in the Request object. Look in the request.path_info or request.path. That will give you the full URL. You can use a regular expression to extract it from there.

import re

input = "articles/1234#slide=5"

m = re.search("#slide=([0-9]*)", input)
try:
    print int(m.group(1))
except ValueError:
    print "didn't get a number"

As Rob said, you should use a get parameter for this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!