简体   繁体   中英

Why to use {%url …%} with slug?

I'm new in Django and making a simple blog to improve my skills. I couldn't understand the purpose of using {% url XXX %} with slug.More precisely;

<a href ="{% url 'theview' post.slug%}">

As i know, url tag above will map the link to view function named 'theview'. And also there is a regular expression filter on url.py to catch clicked link and match it to the appropriate view function. Then why we use {%url%} although there is a filter to notice if the link is slug or not? Isn't it enough to create link like;

<a href="{{post.slug}}">

We use url tag to generate uri with given names and arguments and keyword arguments. If you don't want to use then you need to manually write every url. That's a bad practice.

url(r'^blog/post/(?P<slug>[\w-]+)/$', name='post_detail')

If you have url like above then (Best way to it)

# post.slug = 'learn-python'
<a href="{% url 'post_detail' post.slug %}" > {{ post }}</a>
# is equivalent to
# /blog/post/learn-python/

otherwise we need to write like

<a href="/blog/post/{{post.slug}}/" > {{ post }}</a>

<a href="{{post.slug}}"> will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM