Search code examples
pythondjangodjango-templatesmako

How to set id tag equal to URL name in django


I am trying to set dynamic id attribute to the <body> tag in the HTML.

Something like this - <body id="{{ django_view_name }}>"

I want the id attribute to have the page name, like for the homepage id="home" and for the blog page id="blog" and contact page id="contact"

I don't want to use Javascript or Jquery.

I created a main.html template and then i am inheriting the main template in each of the other templates like index.html templates.

The code in main.htmltag looks like this -

<div class="content-wrapper" id="content">
    <%include file="${static.get_template_path('header.html')}" args="online_help_token=online_help_token" />
    ${self.body()}
</div>

and then on the index.html template i am inheriting like this -

<%inherit file="main.html" />

UPDATE: REQUIRED ADDITIONAL INFORMATION

How can i evaluate the value of ${ request.resolver_match.url_name }. For example if id="${ request.resolver_match.url_name }" evaluates to id="home", then I want to do something like this -

%if ${ request.resolver_match.url_name }=root:
    <div class="container">
else:
    something_else

How can i do this? Any help is really appreciated.


Solution

  • Try this,

    <body id="{{ request.resolver_match.url_name }}"> 
    

    this will generate id based on your url name you defined in urls.py urls

    Update: After the edit of question i see that you used mako templates

    So you need,

    <body id="${ request.resolver_match.url_name }">