我有一个_layout.html模板,如下所示:

<!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>


home.html页通过以下内容扩展了上述内容:

{% 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 %}


该视图是通用的,因为代码检查路径并获取上下文数据和页面...这是一个示例:

# 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)


目录结构:


cust_title正常工作。那么如何以相同的方式传递cust_stylesheet位置和cust_header图像源?

实际渲染类似于以下内容:

<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">

最佳答案

正如@DanielRoseman在评论中所说,您不能在其他标签内调用标签。但是可以使用变量。然后,您可以尝试以下操作:

{% static cust_header %}


那应该正确打印您的字符串。

关于python - 如何将上下文数据传递到sylesheet'src'和image'src'属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31056750/

10-12 21:07