How can an included file know it is included

In django you can include html files in other html files. So my question is there a variable so that the second file knows that it has been included? If not by default can I create one? Here is an example:

a.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>From a.html</h1>
    {% include "b.html" %}
</body>
</html>

b.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {% if included_in_file %}
        <h1>From b.html</h1>
    {% else %}
        <h1>Hello</h1>
    {% endif %}
</body>
</html>

The point is that when a file is included it shows something else than if it is normally used. Or do I just have to make a second file for the same use?

One a.html is processed via a view, it will include b.html. If you want to programmatically handle this for whatever reasons, you could wrap the {% include "b.html" %} into a state defined in your view's context (e.g. include_b)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>From a.html</h1>
    {% if include_b == True %}
        {% include "b.html" %}
    {% endif %}
</body>
</html>

which probably isn't the nicest design in my opinion. Think of it as components you want to render conditionally.

Back to Top