Django URL テンプレート

スポンサーリンク

この記事では、Django テンプレート言語の重要なタグである Django URL テンプレートタグについて知り、それらをどのように使うかについて知ることができます。

スポンサーリンク

URLテンプレートタグとは?

URL テンプレートタグは Django Template Language フレームワークの典型的なタグの一種です。

このタグは特に、テンプレートファイル内にビュー URL を追加するために使われます。

HTML テンプレートファイルでは、URL タグはアンカーと一緒に使われます。

attribute of HTML, which handles all the URLs in HTML

Why do we need the Django URL tag?

When we can add the View URL directly, what’s the purpose of the Django URL template tag?

Let’s look at a simple HTML a href tag.

<a href = "/books/book1">Info about book1</a>

We know that it takes a static URL and allows us to click through to a link.

Views take data from the client via the URL. For example, in the view below:

def View(request,book_id):
    #Code
    return render(request, 'Template.html', {'article_id' : article_id})

In this case, The URL path would be:

path('book/<int:book_id>' , View, name = 'Books_View')

Here the book_id can change from book to book.

Hence, directly adding this URL, whose endpoint depends on book_id, is not practical.  And that’s where the URL tag comes into the picture.

Hands-on with the Template URL tag

To use the Template Tag, we are going to need the Views right!! So let us first create a few simple views to work with.

The URL Template Tag

The URL Template tag syntax is pretty simple:

{% url 'View_Name' variable1 variable2 ... %}

Here the View Name is the name assigned to it in the urls.py file. Variable1, Variable 2, etc., are the input arguments for the particular view.

1. Create the Views

Add the following code in Views.py

def View1(request):
    return render(request, 'page1.html')

Now, we will also create a simple view, taking data input from the user as well. Add the following “ ” to your file as well.

def View2(request,id):
    return render(request, 'page2.html',{'id':id})

The URL paths for both the Views will be:

path('page/', View1, name = 'webpage1'),
path('page/<int:id>', View2, name = 'webpage2'),

You can learn more about setting up views in the Django views article.

2. Create the Template file

Now create a Template file “page1.html ” and add the code into the file.

<h2> The Webpage 1 </h2>
<a href = "{% url 'webpage2' id=2 %}"> Click Here for book 2 </a>

Lets create the “page2.html” as well.

<H2> The Webpage2 </H2>
<a href = "{% url 'webpage1' %}"> Go back </a>

Implementing Django URL Tag

Enough with the coding, let us now run the program. Hence go to the terminal and fire up your server.

python manage.py runserver

Go to the URL “/ page”:

Webpage 1
Webpage 1

Click the link and check

Webpage 2
Webpage 2

That’s it, see how easy it is to use the URL template tag !!

Conclusion

That’s it, guys !! This was all about the URL Template Tag. Do check out the Django Templates article as well as the DTL article for more information about Templates.

See you in the next article !! Till then, Keep Coding !!

タイトルとURLをコピーしました