Search code examples
pythondjangometa-tags

Unable to write Dynamic meta tag in django


Hello all i want to print dynamic meta tag values in django. i have _header.html as partial file which is common to all the pages. In that header file i want to add meta tags. The header file is included in base.html and base extends all the other pages i want different meta tags for different pages. the below code is for _header.html file

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
"here i want dynamic meta tags"
<title>Random Blog</title>
<link rel="stylesheet" 
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="{% static 'css/main.css' %}">
</head>

Solution

  • You can have a block meta in your main html. Then for each template view, you can add the meta in the context (or directly inside each html)

    {% load static %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    {% block meta %}
    "here i want dynamic meta tags"
    {% endblock meta %}
    <title>Random Blog</title>
    <link rel="stylesheet" 
     href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="{% static 'css/main.css' %}">
    </head>
    

    then in a view

    def some_view(request):
        my_custom_meta = 'Some custom meta'
        return render(request, 'my_template.html', {'my_custom_meta': my_custom_meta})
    

    Then in your other template:

    {% include base.html %}
    {% block meta %}
    {{ my_custom_meta }}
    {% endblock meta %}