skip to Main Content

I’m working on a djanog project and i want to render dynamic meta tags and titles for every page in it.
for now i’m trying to do it like this
i have added block in header.html file like this

{% block seo %}
{% endblock %}

hierarchy of main template (from which all other templates are extending)

{% include 'header.html' %}
{% include 'menu.html' %}
{% block body %}
{% endblock %}
{% include 'footer.html' %}

now on app templates i’m trying to render those seo tags like this

{% extends 'main.html' %}
{% block seo %}
<title>example.cpm</title>
<mete name="description" content="lorem ipsum">
{% endblock %}

but this approach is not working for me, please help me in this regard

3

Answers


  1. The Django template engine does not support this. You have to place the seo block placeholder in your main template, otherwise it won’t be rendered when extending.

    {% block seo %}
    {% endblock %}
    {% include 'menu.html' %}
    {% block body %}
    {% endblock %}
    {% include 'footer.html' %}
    
    Login or Signup to reply.
  2. You should define this to the header.html :

    {% block seo %}
        <title>example.cpm</title>
        <meta name="description" content="lorem ipsum">
    {% endblock %}
    

    And there is no need to redefine the block seo on the app template.

    According to the documentation, The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process.

    Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered – not blocks that can be overridden by, for example, an extending template.

    Login or Signup to reply.
  3. the simplest way is to create fields containing your seo
    and then render them to template

    {% block seo %}
        <title>example.cpm</title>
        <meta name="description" content="lorem ipsum">
    {% endblock %}
    

    now lets start view function

    def meta(request,pk):
         meta=Meta.objects.get(id=pk)
         return render(request, 'index.html', {'meta':meta})
    
    % block seo %}
        <title>example.cpm</title>
        <meta name="description" content="lorem ipsum">
    {% endblock %}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search