Login

Tag "templatetags"

Snippet List

Enhancing template tags with "as variable" syntax

Add the decorator to an already defined templatetag that returns a Node object: @with_as def do_current_time(parser, token): ... return a_node The decorator will patch the node's render method when the "as" syntax is specified and will update the context with the new variable. The following syntaxes are available: {% current_time %} {% current_time as time %} {{ time }}

  • templates
  • templatetags
Read More

Absolute URL Templatetag

The {% url %} templatetag is awesome sometimes it is useful to get the full blown URL with the domain name - for instance for links in emails. The **{% absurl %}** templatetag mirrors the behaviour of {% url %} but inserts absolute URLs with the domain of the current Site object. Usage: {% absurl viewname %} >>> http://www.example.org/my/view/

  • url
  • templatetags
  • absolute
  • uri
Read More

Truncate string after a given number of chars keeping whole words

Truncates a string after a given length, keeping the last word complete. This filter is more precise than the default `truncatewords` filter. Words length vary too much, 10 words may result in 40 or 70 characters, so cutting by character count makes more sense. There is a [blog post](http://ricobl.wordpress.com/2008/12/23/templates-django-filtro-truncatewords-melhorado/) about this snippet (in Portuguese).

  • template
  • filter
  • templatetag
  • truncate
  • templatetags
  • words
Read More
Author: rix
  • 5
  • 6

Auto Generate/Save Thumbnails using Template Filter (scale max_x, max_y, or both)

Couldn't get the original to work, and wanted more functionality (scale on x or y coordinates) <img src="{{ object.image.url }}" alt="original image"> <img src="{{ object.image|thumbnail:"250w" }}" alt="image resized to 250w x (calculated/scaled)h "> <img src="{{ object.image|thumbnail:"250h" }}" alt="image resized to (calculated/scaled)w x 250h h "> <img src="{{ object.image|thumbnail:"250x200" }}" alt="image resized to 250wx200h "> <img src="{{ object.image|thumbnail }}" alt="image resized to default 200w (or whatever you default it to) format"> Original http://www.djangosnippets.org/snippets/192/ Adapted http://www.djangosnippets.org/snippets/955/ Sampled From: http://batiste.dosimple.ch/blog/2007-05-13-1/ http://vaig.be/2008/05/17/stdimagefield-improved-image-field-for-django/

  • template
  • filter
  • image
  • template-filter
  • thumbnail
  • templatetags
Read More

Add multiple parameters to the current url

Add multiple parameters to the current url.<br /> **Usage:**<br /> `{% addparam name1 value1 name2 value2 %}`<br /> or<br /> `{% addparam "name1" value1 "name2" value2 %}`<br /> variable can be use inplace of names and values<br /> example: <br />`{% addparam "view" message.id %}`

  • url
  • templatetags
  • parameter
Read More

Google Charts Templatetags (Python)

The core templatetags for my project [google-chartwrapper](http://code.google.com/p/google-chartwrapper/). It is an easy method of creating dynamic GoogleCharts from the [GoogleChartAPI](http://code.google.com/apis/chart/). To get the most recent version: `svn checkout http://google-chartwrapper.googlecode.com/svn/trunk/` and run `python setup.py` in the downloaded trunk directory. There is an included django project there with the [ChartsExamples](http://code.google.com/p/google-chartwrapper/wiki/ChartExamples) all worked out in django templates

  • templatetags
  • google
  • chart
Read More

Templatetag startswith + message tuned

Template: `<div id="messageBox_{{ forloop.counter0 }}" style="border:1px solid #ccc;background-color:white" onclick="document.getElementById ('messageBox_{{ forloop.counter0 }}').style.display = 'none';"> {% ifstartswith message "#ok#" %} <font color="green"> {% endifstartswith %} {% ifstartswith message "#error#" %} <font color="red"> {% endifstartswith %} {{ message|cut:"#ok#"|cut:"#error#" }} </font> </div>` In a view you can now do something like that: ` request.user.message_set.create(message="#ok#Hello User, this is a ok message!")`

  • template
  • templatetags
  • message
Read More

Google Charts Templatetags (HTML)

Example usage of the GChartWrapper.charts module for creating dynamic charts with templatetags. It is an easy method of creating dynamic GoogleCharts from the [GoogleChartAPI](http://code.google.com/apis/chart/). The project is located at [google-chartwrapper](http://code.google.com/p/google-chartwrapper/). To get the most recent version: `svn checkout http://google-chartwrapper.googlecode.com/svn/trunk/` and run `python setup.py` in the downloaded trunk directory. There is an included django project there with the [ChartsExamples](http://code.google.com/p/google-chartwrapper/wiki/ChartExamples) all worked out in django templates

  • templatetags
  • google
  • chart
Read More

Tags & filters for rendering search results

Use these tags and filter when you're rolling your own search results. This is intended to be a whole templatetags module. I keep it in my apps as `templatetags/search.py`. These should not be used to perform search queries, but rather render the results. ### Basics There are three functions, each has both a tag *and* a filter of the same name. These functions accept, at a minimum, a body of text and a list of search terms: * **searchexcerpt**: Truncate the text so that each search term is shown, surrounded by some number of words of context. * **highlight**: Wrap all found search terms in an HTML span that can be styled to highlight the terms. * **hits**: Count the occurrences of the search terms in the text. The filters provide the most basic functionality as described above, while the tags offer more options as arguments, such as case sensitivity, whole word search, and saving the results to a context variable. ### Settings Defaults for both the tags and filters can be changed with the following settings. Note that these settings are merely a convenience for the tags, which accept these as arguments, but are necessary for changing behavior of the filters. * `SEARCH_CONTEXT_WORDS`: Number of words to show on the left and right of each search term. Default: 10 * `SEARCH_IGNORE_CASE`: False for case sensitive, True otherwise. Default: True * `SEARCH_WORD_BOUNDARY`: Find whole words and not strings in the middle of words. Default: False * `SEARCH_HIGHLIGHT_CLASS`: The class to give the HTML span element when wrapping highlighted search terms. Default: "highlight" ### Examples Suppose you have a list `flatpages` resulting from a search query, and the search terms (split into a list) are in the context variable `terms`. This will show 5 words of context around each term and highlight matches in the title: {% for page in flatpages %} <h3>{{ page.title|highlight:terms }}</h3> <p> {% searchexcerpt terms 5 %} {{ page.content|striptags }} {% endsearchexcerpt %} </p> {% endfor %} Add highlighting to the excerpt, and use a custom span class (the two flags are for case insensitivity and respecting word boundaries): {% highlight 1 1 "match" %} {% searchexcerpt terms 5 1 1 %} {{ page.content|striptags }} {% endsearchexcerpt %} {% endhighlight %} Show the number of hits in the body: <h3>{{ page.title }} (Hits: {{ page.content|striptags|hits:terms }}) </h3> All tags support an `as name` suffix, in which case an object will be stored in the template context with the given name; output will be suppressed. This is more efficient when you want both the excerpt and the number of hits. The stored object depends on the tag: * **searchexcerpt**: A dictionary with keys "original" (the text searched), "excerpt" (the summarized text with search terms), and "hits" (the number of hits in the text). * **searchcontext**: A dictionary with keys "original", "highlighted", and "hits", with obvious values. * **hits**: Just the number of hits, nothing special. Getting both the hits and the excerpt with "as": {% searchexcerpt terms 3 as content %} {{ page.content|striptags }} {% endsearchexcerpt %} <p>Hits: {{ content.hits }}<br>{{ content.excerpt }}</p> ### More For more examples see [Brian Beck's Text Adventure][announcement]. [announcement]: http://blog.brianbeck.com/post/29707610

  • filter
  • tag
  • search
  • templatetags
  • context
  • highlight
  • excerpt
Read More

Currency filter

Formats a number in the local currency format. E.g., if `foo` is equal to `49277`, then > ` {{ foo|currency }}` would print > `$49,277` If your locale is the U.S. You can use this filter in your templates as described in the [Django documentation](http://www.djangoproject.com/documentation/templates_python/)

  • filter
  • templatetags
  • money
  • currency
  • dollars
Read More

"for" template tag with support for "else" if array is empty

This is a customized version of the default `for` template tag which takes an optional `{% else %}` clause that will be displayed if the given array is empty. from django.template import * >>> t1 = Template(""" {% load mytags %} {% for athlete in athlete_list %} {{ athlete }} {% else %} No athlete in list! {% endfor %} """) >>> c1 = Context( {'athlete_list': ['me', 'myself', 'I'] }) >>> t1.render(c1) u'me myself I ' >>> c2 = Context({}) >>> t1.render(c2) u'No athlete in list!' If you want to automatically override the builtin `for` template-tag add it to the builtins: from django.template import add_to_builtins add_to_builtins('python.path.to.mytags')

  • template
  • tags
  • template-tag
  • templatetags
  • forloop
Read More

Breadcrumbs for flatpages

Custom template filter to generate a breadcrumb trail for a flatpage. Say you have a series of flatpages with URLs like /trunk/branch/leaf/ etc. This filter looks at the URL of a given flatpage, figures out which of the leftwards text chunks correspond to other flatpages, and generates a string of anchored HTML. Usage: {% load make_breadcrumb_trail %} {{ flatpage.url|crumbs:flatpage.title }}

  • filter
  • templatetags
  • breadcrumb
  • flatpage
Read More
Author: jca
  • 3
  • 14

Code syntax highlighting templatetag

Replaces <code> blocks with syntax highlighted code. Use CSS to actually get the colours you want, look at pygments documentation for extracting css for various styles. This snippet has the advantage of falling back on <pre> if anything goes wrong, and attempting to guess the syntax of code, falling back on python.

  • templatetag
  • pygments
  • highlighting
  • beautifulsoup
  • templatetags
  • syntax
  • syntax-highlightin
Read More

35 snippets posted so far.