djblets.util.templatetags.djblets_utils¶
- definevar(context, nodelist, varname, *options)[source]¶
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 of unicode, 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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
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
attrname (unicode) – The name for the HTML attribute.
*options (list unicode, optional) –
A list of options passed. This supports the following:
nocondense
:Preserves all whitespace in the value.
block_content (unicode) – The block content to render for the attribute value.
- 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)[source]¶
HTML-escape all spaces with
and newlines with<br />
.- Parameters
value (unicode) – The value to escape.
- Returns
The same text, but escaped.
- Return type
unicode
Example
<div class="text"> {{obj.description|escapespaces}} </div>
- ageid(timestamp)[source]¶
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
unicode
Example
<div class="{% ageid obj.timestamp %}"> {{obj.timestamp}} </div>
- user_displayname(user)[source]¶
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
unicode
Example
Welcome, {{user|user_displayname}}!
- contains(container, value)[source]¶
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)[source]¶
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
obj (object) – The object that contains the attribute.
name (unicode) – The name of the key to look up in the container.
- 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)[source]¶
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)[source]¶
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)[source]¶
Indent a string by the specified number of spaces.
This is especially useful for preformatted content.
- Parameters
value (unicode) – The value containing text to indent.
numspaces (int, optional) – The number of spaces to indent the text. Defaults to 4 spaces.
- Returns
The indented text.
- Return type
unicode
Example
<pre> The traceback was: {{traceback|indent:2}} </pre>
- basename(path)[source]¶
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
unicode
Example
The file is contained within <tt>{{path|basename}}</tt>.
- range_filter(value)[source]¶
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)[source]¶
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
unicode
Example
Welcome, {{user|realname}}!
- startswith(s, prefix)[source]¶
Return whether a value starts with another value.
- Parameters
s (unicode) – The string to check.
prefix (unicode) – The prefix to check for.
- Returns
True
if the string starts with the given prefix.- Return type
Example
{% if key|startswith:"__" %} .. {% endif %}
- endswith(s, suffix)[source]¶
Return whether a value ends with another value.
- Parameters
s (unicode) – The string to check.
suffix (unicode) – The suffix to check for.
- Returns
True
if the string ends with the given suffix.- Return type
Example
{% if filename|endswith:".json" %} .. {% endif %}
- paragraphs(text)[source]¶
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
unicode
Example
<article> {{description|paragraphs}} </article>
- split(s, delim=',')[source]¶
Split a string into a list.
The string can be split by any specified delimiter, and defaults to a comma.
- Parameters
s (unicode) – The string to split.
delim (unicode, optional) – The delimiter to split by. Defaults to
,
.
- Returns
The resulting list of tokens from the string.
- Return type
Example
{% for token in str|split:'\t' %} .. {% endfor %}
- querystring_with(context, attr, value)[source]¶
Return the current page URL with a new query string argument added.
This makes it easy to add to or replace part of a query string for the current page’s URL, which may already contain a query string.
If the page URL already has a query string, a new item is added in the form of
&attr=value
. If it doesn’t have a query string, this will start a new one in the form of?attr=value
.If the attribute already exists in the query string, its value will be replaced.
- Parameters
context (django.template.context.RequestContext) – The Django template rendering context.
attr (unicode) – The name of the attribute for the new query string argument.
value (unicode) – The value of the attribute for the new query string argument.
- Returns
The new URL with the modified query string.
- Return type
unicode
Example
<a href="{% querystring_with "sorted" "1" %}">Sort</a>
- querystring(context, mode, *args)[source]¶
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
unicode
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>