How to identify an anchor in a url in Django?

后端 未结 3 1031
猫巷女王i
猫巷女王i 2020-12-07 04:56

I\'m doing a slideshow and each slide has a url format like this: articles/1234#slide=5. I want to retrive the slide=5 part from the url in my url.

相关标签:
3条回答
  • 2020-12-07 05:06

    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?

    0 讨论(0)
  • 2020-12-07 05:06

    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.

    0 讨论(0)
  • 2020-12-07 05:14

    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

    0 讨论(0)
提交回复
热议问题