Search code examples
pythondjangotemplate-context

How can I pass context data to sylesheet 'src' and image 'src' attributes?


I have a _layout.html template as follows:

<!DOCTYPE html>
{% load staticfiles %}

<html lang="en">
    <head>
        {% block linkcss %}{% endblock %}
        <title>{% block title %}{% endblock %}</title>
        <script type="text/javascript" src="{% static 'scripts/jquery-2.1.3.min.js' %}"></script>
        {% block scripts %}{% endblock %}
    </head>
    <body>
        {% block head %}{% endblock %}
        <table class="page_content">
            <tr>
                <td>
                    <div id="content">
                        {% block content %}{% endblock %}
                    </div>
                </td>
            </tr>
        </table>
    </body>
</html>

The page home.html extends the above with the following:

{% extends "generic/_layout.html" %}
{% load staticfiles %}

{% block title %}{{ cust_title }}{% endblock %}
{% block linkcss %}<link rel="stylesheet" type="text/css" href="{% static '{{ cust_stylesheet }}' %}" />{% endblock %}

{% block scripts %}
<script type="text/javascript">
</script>
{% endblock %}

{% block head %}
<table class="head">
    <tr>
        <td class="center">
            <img src="{% static '{{ cust_header }}' %}">
        </td>
    </tr>
</table>
{% endblock %}

{% block content %}
<table class="content">
        <thead align="center">
            <tr>
                <th colspan="3" style="text-align: center">{{ cust_message }}</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
{% endblock %}

The view is generic in that the code checks the path and gets the context data and page ...here is an example:

# customer configurations constants:
CUSTOMER_CONFIGS = {
    'samplewebpage': {
        'context': {
            'cust_title': "Sample Customer Page",
            'cust_stylesheet': "SampleWeb/style.css",
            'cust_header': "SampleWeb/sample_header.png",
            'cust_message': "Welcome to Sample Web Page"
        },
        'home': "SampleWebPage/home.html"
    },
}

# generic view:
def index(request):
    path = request.path.replace("/", "")

    context = CUSTOMER_CONFIGS[path]['context']
    page = CUSTOMER_CONFIGS[path]['home']

    return render(request, page, context)

Directory structure: directory structure

The cust_title works properly. So how can I pass the cust_stylesheet location and cust_header image source the same way?

The actual rendering resembles the following:

<link rel="stylesheet" type="text/css" href="/static/%7B%7B%20cust_stylesheet%20%7D%7D" />  

<img src="/static/%7B%7B%20cust_header%20%7D%7D">

Solution

  • As @DanielRoseman says in comments You can't call tags inside other tags. But it is possible to use variables. Then you could try this:

    {% static cust_header %}
    

    That should print your string properly.