Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

python - jinja2 set background image

I am trying to set the background image using jinja2. I have managed to serve my file from my dev server and can post the image in the document, but I want it to form a nice background with everything else on top.

As an example, I tried this :

{% extends "layout.html" %}

{% block body %}
  {% if current_user.is_authenticated %}
    {% if commPageData.background_image %}    
        <body background="{{'/images/'+commPageData.background_image}}">
    {% else %}
        <body>
    {% endif %}
            A thing
         </body>

I have a css file and a layout file that gives the default behaviour for a template. How can I have a nice background image which I am serving?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You seem to be trying to tell the front end to use application routing without passing it the right commands. I'm assuming you're using Flask. Really, there are two ways (that I can think of) to slice this bread, and it just depends on you. The first is just using standard html and not embedding python to route the app to look for the file, and looks like:

<body background="/path/to/image.jpg">

But, if you want to take advantage of the framework and the template, then you should use the built in method url_for

It looks something like this:

<body background="{{ url_for('static', filename=commPageData.background_image) }}">

'static' being the directory in the application where this image lives.

Now, I'm not sure where commPageData.background_image is coming from in your app. My code snip assumes it is being served as a value it will recognize if passed back to the logic, if that makes sense, and it needs to be where you tell the url_for method looks for it, even when dynamically generated. If you actually have a specific image you want to render as the background, it needs to be specified appropriately:

<body background="{{ url_for('static', filename='image.jpg') }}">

Of course, has been deprecated in HTML5 and may not render appropriately in many browser. It is much preferred to use CSS instead with

<body style="background:url({{'images/'+commPageData.background_image}});"> 

or put it directly in your CSS file


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...