djblets.util.templatetags.djblets_utils¶
Miscellaneous utility template tags.
- definevar(context, nodelist, varname, *options)¶
Define a variable for later use in the template.
The variable defined can be used within the same context (such as the same block or for loop). This is useful for caching a portion of a template that would otherwise be expensive to repeatedly compute.
New in version 2.0: Added the new
global
option.New in version 1.0: Added new
strip
,spaceless
, andunsafe
options.- Parameters:
varname (
unicode
) – The variable name.*options (
list
ofunicode
, optional) –A list of options passed. This supports the following:
global
:Register the variable in the top-level context, for other blocks to see.
Note that the ordering of registration and usage is important, so consumers are advised to have a dedicated template block for this purpose. Also note that if a later block defines a variable with the same name, that will take precedence.
strip
:Strip whitespace at the beginning/end of the value.
spaceless
:Strip whitespace at the beginning/end and remove all spaces between tags. This implies
strip
.unsafe
:Mark the text as unsafe. The contents will be HTML-escaped when inserted into the page.
block_content (
unicode
) – The block content to set in the variable.
Example
{% definevar "myvar1" %} {% expensive_tag %} {% enddefinevar %} {% definevar "myvar2" spaceless %} <div> <a href="#">Click me!</a> </div> {% enddefinevar %} {{myvar1}} {{myvar2}}
- ifuserorperm(context, nodelist, user, perm)¶
Render content only for a given user or a user with a given permission.
The content will only be rendered if the logged in user matches the specified user, or the logged in user has the specified permission.
This is useful when you want to restrict some content to the owner of an object or to a privileged user that has the abilities of the owner.
- Parameters:
user (
django.contrib.auth.models.User
) – The user to limit access to, unless the logged in user has the specified permission.perm (
unicode
) – The permission to require, if the logged in user does not match the specified user.block_content (
unicode
) – The block content to render.
- Returns:
The content, if the user or permission matches. Otherwise, no content will be returned.
Example
{% ifuserorperm myobject.user "myobject.can_change_status" %} Owner-specific content here... {% endifuserorperm %}
- ifnotuserandperm(context, nodelist, user, perm)¶
Render content if a user and permission don’t match the logged in user.
This is the opposite of
{% ifuserorperm %}
. It will only render content if the logged in user is not the specified user and doesn’t have the specified permission.- Parameters:
user (
django.contrib.auth.models.User
) – The user who cannot see the provided content.perm (
unicode
) – Any user with this permission will not see the provided content.block_content (
unicode
) – The block content to render.
- Returns:
The content, if neither the user nor permission matches. Otherwise, no content will be returned.
Example
{% ifuserorperm myobject.user "myobject.can_change_status" %} Owner-specific content here... {% endifuserorperm %} {% ifnotuserandperm myobject.user "myobject.can_change_status" %} Another owner-specific content here... {% endifnotuserandperm %}
- include_as_string(context, template_name)¶
Include the contents of a template as an escaped string.
This is primarily for use with JavaScript. It allows another template to be rendered (with the current context) and returned as an escaped string.
- Parameters:
template_name (
unicode
) – The name of the template to render.- Returns:
The escaped content from the template.
Example
<script> var s = {% include_as_string "message.txt" %}; </script>
- attr(context, nodelist, attrname, *options)¶
Set an HTML attribute to a value if the value is not an empty string.
This is a handy way of adding attributes with non-empty values to an HTML element without requiring several {% if %} tags.
The contents will be stripped and all whitespace within condensed before being considered or rendered. This can be turned off (restoring pre-1.0 behavior) by passing
nocondense
as an option.Changed in version 1.0: Prior to this release, all whitespace before/after/within the attribute value was preserved. Now
nocondense
is required for this behavior.The value is now escaped as well. Previously the value was assumed to be safe, requiring the consumer to escape the contents.
- Parameters:
- Returns:
An attribute in the form of
key="value"
, if the value (the block content) is not empty.
Example
<div{% attr "class" %}{{obj.name}}{% endattr %}> <div{% attr "data-description" nocondense %} Space-sensitive whitespace {% endattr %}>
- escapespaces(value)¶
HTML-escape all spaces with
and newlines with<br />
.- Parameters:
value (
unicode
) – The value to escape.- Returns:
The same text, but escaped.
- Return type:
Example
<div class="text"> {{obj.description|escapespaces}} </div>
- ageid(timestamp)¶
Return an ID based on the difference between now and a timestamp.
This can be used to help show the age of an item in days. It will generate an ID in the form of
agenum
ranging fromage1
(today) throughage5
(4+ days old).This is a specialty function, and is not expected to be useful in many cases.
- Parameters:
timestamp (
datetime.datetime
) – The timestamp to compare to.- Returns:
The ID. One of
age1
,age2
,age3
,age4
, orage5
.- Return type:
Example
<div class="{% ageid obj.timestamp %}"> {{obj.timestamp}} </div>
- user_displayname(user)¶
Return the display name of a user.
If the user has a full name set, it will be returned. Otherwise, the username will be returned.
- Parameters:
user (
django.contrib.auth.models.User
) – The user whose full name or username will be returned.- Returns:
The full name of the user, if set, or the username as a fallback.
- Return type:
Example
Welcome, {{user|user_displayname}}!
- contains(container, value)¶
Return whether the specified value is in the specified container.
This is equivalent to a
if value in container
statement in Python.- Parameters:
- Returns:
True
if the value is in the container. Otherwise,False
.- Return type:
Example
{% if usernames|contains:"bob" %} Hi, Bob! {% endif %}
- getattr_filter(obj, name)¶
Return the attribute of a specified name from an object.
This is equivalent to a
getattr(obj, name, None)
statement in Python.New in version 2.0.
- Parameters:
- Returns:
The attribute value.
- Return type:
Example
{% for name in attrs %} {{name}}: {{obj|getattr:name}} {% endfor %} {{obj|getattr:other_attr|default_if_none:"my fallback"}}
- getitem(container, key)¶
Return the value of a specified key from a container.
This is equivalent to a
container[key]
statement in Python. The container must support this operator.- Parameters:
- Returns:
The content within the container.
- Return type:
Example
{% for key in keys %} {{key}}: {{obj|getitem:key}} {% endfor %}
- exclude_item(container, item)¶
Return a list with the given item excluded.
- Parameters:
- Returns:
The list with the item excluded.
- Return type:
Example
{% for item in mylist|exclude_item:"special" %} ... {% endfor %}
- indent(value, numspaces=4)¶
Indent a string by the specified number of spaces.
This is especially useful for preformatted content.
- Parameters:
- Returns:
The indented text.
- Return type:
Example
<pre> The traceback was: {{traceback|indent:2}} </pre>
- basename(path)¶
Return the base name of a path.
This will be computed based on the path rules from the system the server is running on.
- Parameters:
path (
unicode
) – The path for which to retrieve the base name.- Returns:
The base name of the path.
- Return type:
Example
The file is contained within <tt>{{path|basename}}</tt>.
- range_filter(value)¶
Turn an integer into a range of numbers.
This is useful for iterating with the “for” tag.
- Parameters:
value (
int
) – The number of values in the range.- Returns:
The list of numbers in the range.
- Return type:
Example
{% for i in 10|range %} {{i}} {% endfor %}
- realname(user)¶
Return the real name of a user, if available, or the username.
If the user has a full name set, this will return the full name. Otherwise, this returns the username.
Deprecated since version 0.9: This is deprecated in favor of
user_displayname()
.- Parameters:
user (
django.contrib.auth.models.User
) – The user whose full name or username will be returned.- Returns:
The full name of the user, if set, or the username as a fallback.
- Return type:
Example
Welcome, {{user|realname}}!
- startswith(s, prefix)¶
Return whether a value starts with another value.
- Parameters:
- Returns:
True
if the string starts with the given prefix.- Return type:
Example
{% if key|startswith:"__" %} .. {% endif %}
- endswith(s, suffix)¶
Return whether a value ends with another value.
- Parameters:
- Returns:
True
if the string ends with the given suffix.- Return type:
Example
{% if filename|endswith:".json" %} .. {% endif %}
- paragraphs(text)¶
Return an HTML paragraph for each line of text.
This iterates through the lines of text given and wraps each in a
<p>
tag.This expects that each paragraph in the string will be on its own line. Blank lines are filtered out.
The text is expected to be HTML-safe already.
- Parameters:
text (
unicode
) – The text containing at least one line of content.- Returns:
The resulting HTML output.
- Return type:
Example
<article> {{description|paragraphs}} </article>
- split(s, delim=',')¶
Split a string into a list.
The string can be split by any specified delimiter, and defaults to a comma.
- Parameters:
- Returns:
The resulting list of tokens from the string.
- Return type:
Example
{% for token in str|split:'\t' %} .. {% endfor %}
- querystring(context, mode, *args)¶
Return current page URL with new query string containing multiple parameters.
- Parameters:
context (
django.template.context.RequestContext
) – The Django template rendering context.mode (
unicode
) –How the querystring will be modified. This should be one of the following values:
'update'
:Replace the values for the specified key(s) in the query string.
'append'
:Add new values for the specified key(s) to the query string.
'remove'
:Remove the specified key(s) from the query string.
If no value is provided, all instances of the key will be removed.
*args (
tuple
) – Multiple querystring fragments (e.g.,foo=1
) that will be used to update the initial querystring.
- Returns:
The new URL with the modified query string.
- Return type:
Example
<a href="{% querystring "update" 'a=1' 'b=2' %}">Sort</a> <a href="{% querystring "append" 'a=1' 'b=2' %}">Sort</a> <a href="{% querystring "append" 'a=1&a=2' %}">Sort</a> <a href="{% querystring "remove" 'a' %}">Sort</a>