【问题标题】:Tornado: How to write in template when image is used for background-image?Tornado:当图像用于背景图像时如何在模板中写入?
【发布时间】:2014-01-01 12:29:44
【问题描述】:

例如,我将图像的 url 渲染为“exmaple.html”。

self.render("example.html", image=image)

然后在模板中:如果我想将它用于背景图像,该怎么写?

我在 CSS 文件中试试这个:

background-image: url({{image}});

但它不起作用。

非常感谢您的帮助!

【问题讨论】:

    标签: css templates background-image render tornado


    【解决方案1】:

    您将 css 作为静态文件还是模板提供服务?您必须将其设为模板才能解释像 {{image}} 这样的表达式。 (但要小心 - Tornado 对转义文本以包含在 CSS 中一无所知,因此如果图像可能包含任何用户提供的文本,您必须自己验证或转义它)。

    不过,与其将您的 CSS 文件设为模板,不如将其保持为静态并将不同的部分放入 HTML 中。如果图像是几种可能性之一,您可以为每个图像定义一个类并在 html 中引用该类。如果列出的可能性太多,内联样式属性可能是最好的方法(但请参阅之前关于转义的评论)

    【讨论】:

      【解决方案2】:

      在您的基本模板中添加一个 CSS 块。然后你可以使用它来指定 CSS 规则。

      base_template.html:

      <html>
      <head>
          <title>Some Title</title>
          {% block css %}{% end %}
      </head>
      <body>
              {% block body %}{% end %}
      </body>
      </html>
      

      在要渲染的文件中:

      {% extends "base_template.html" %}
      {% block css %}
      <style type="text/css">
          background-image: url( {{ image }} );
      </style>
      {% end %}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-07
        • 2013-07-08
        • 1970-01-01
        • 2021-02-20
        • 2017-01-27
        • 2016-11-26
        • 2017-04-26
        • 1970-01-01
        相关资源
        最近更新 更多