django1.4模版学习:static
static
To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you’re using RequestContext or not.
{% load static %}
<img src="{% static "images/hi.jpg" %}" />
It is also able to consume standard context variables, e.g. assuming a user_stylesheet variable is passed to the template:
{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen" />
Note
The staticfiles contrib app also ships with a static template tag which uses staticfiles' STATICFILES_STORAGE to build the URL of the given path. Use that instead if you have an advanced use case such as using a cloud service to serve static files:
{% load static from staticfiles %}
<img src="{% static "images/hi.jpg" %}" />
get_static_prefix
If you’re not using RequestContext, or if you need more control over exactly where and how STATIC_URL is injected into the template, you can use the get_static_prefix template tag instead:
{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" />
There’s also a second form you can use to avoid extra processing if you need the value multiple times:
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
<img src="{{ STATIC_PREFIX }}images/hi.jpg" />
<img src="{{ STATIC_PREFIX }}images/hi2.jpg" />
get_media_prefix
Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.:
<script type="text/javascript" charset="utf-8">
var media_path = '{% get_media_prefix %}';
</script>

最新评论