Login

Tag "template"

Snippet List

A dict template tag

When you need to include a specific javascript file/code snippet in your page, it's always better to do it at the bottom of your page to avoid to block the rendering too soon. This tag provide you a nice way to include and launch only what is needed: Example in an included template that need to display google maps: {% dict js_file google_api %} <script src="http://www.google.com/jsapi?key={{ MAPS_API_KEY }}" type="text/javascript" charset="utf-8"></script> <script src="{{MEDIA_URL}}js/map.display.js" type="text/javascript">...</script> {% enddict %} {% dict js_code link_map %} $('.show-map').click(function() { ... }); $('.hide-map').click(function() { ... }); {% enddict %} Finaly you just have to add this to the very bottom of your base.html file: .... </body> {% for k,v in js_file.items %} {{v}} {% endfor %} <script type="text/javascript"> /* <![CDATA[ */ {% for k,v in js_code.items %} {{v}} {% endfor %} /* ]]> */ </script> </html>

  • template
  • javascript
  • dict
  • stack
Read More

Preview tag for fields with choices

django.contrib.formtools in preview displaying only field.data by default. Its not convenient to see integer value for fields with radio buttons or select choices. This custom tag trying to show string value from choices if available.

  • template
  • tag
  • newforms
  • preview
Read More

Render to file

As a demo, I was asked to write a `render_to_file()` function to load a template and render it to a file. Turns out it's amazingly easy, and I think it's a neat trick to have in your bag of tools.

  • template
  • render
  • file
Read More

Passing values to a method from a template

A simple trick to let a function be called with exactly ONE argument from a Django template, by passing it via an attribute. Example: class SearchResult(object): @template_callable def highlighted(self, field): return self._xappy_result.highlight(field) result = SearchResult() result.highlighted.title {{ result.highlighted.title }}

  • template
  • templates
  • method
  • call
  • arguments
Read More

Lazily lookup dynamically for templates

If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data. These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example: from lazy_lookup import lazy_lookup_dict def some_view(request): users = User.objects.values('id', 'username') articles = Article.objects.values('user', 'title', 'body') articles = dict([(x['user'], x) for x in articles]) return render_to_response('some_template.html', {'data': lazy_lookup_dict(users, key=lambda x: x['id'], article=articles, item_name='user')}) Then in the template layer you'd write something like: {% for user_data in data %} {{ user_data.user.username }}, {{ user_data.article.title }} {% endfor %}

  • template
  • dynamic
  • lookup
  • lazy
  • dynamic-lookup
Read More

cache_smart template tag

cache_smart template tag is a drop in replacement for default cache tag by Django but with the added bonus to be more resistant against dog-pile/stampeding effect. This snippet uses a extra cache entry to store a stale time so we don't have to pickle/unpickle to store this extra value. If this cache entry returns None, as in expired it will reset the stale timeout 30 seconds in the future so further calls will just return the old value while this request is regenerating the new value. **warning** Don't use both cache template tags!

  • template
  • cache
  • memcached
Read More

django_template decorator

Easy way to caching template. Very simple usage: @django_template("my_site.html") def master_home(request): variables = { 'title' : "Hello World!" } return variables

  • template
  • render
  • decorator
Read More

Twitter status tag

Requires the twitter module (easy_install python_twitter). Your project settings file should define TWITTER_USERNAME. Call the tag like: ` {% get_twitter_status as tweet tweet_time tweet_url %} <p><q cite="{{ tweet_url }}">{{ tweet }}</q> ({{ tweet_time }})</p> ` **EDIT**: I've also included an alternative method as suggested in the comments. Called with: ` {% get_twitter_status as tweet %} <p><q cite="{{ tweet.url }}">{{ tweet.status }}</q> ({{ tweet.time }})</p> `

  • template
  • twitter
Read More

Recurse template tag for Django

[Original and further information available from here.](http://www.undefinedfire.com/articles/recursion-in-django-templates/) **v1.1 Update (20/04/08):** Added the ability to recurse single elements as well as automatic skipping of empty elements. Most of the tags are self explanatory, the only one that may cause confusion is the main `{% recurse %}` one. The format for this tag is `{% recurse [children] with [parent] as [child] %}` where “[children]” is the property that contains the children of the current element, “[parent]” is your starting element and “[child]” is the variable named used in the loop. Example usage: {% load recurse %} ... Headers and stuff ... {% recurse category.category_set.all with categories as category %} <ul> {% loop %} <li> <h{{ level }}>{{ category.title }}</h{{ level }}> {% child %} </li> {% endloop %} </ul> {% endrecurse %} ... The rest of the page ...

  • template
  • templatetag
  • recursion
Read More

Make anything into a template

This is a quick and dirty way to reuse the Django templating system for your own ends. Just pop in the familiar Django template syntax into whatever content you like and any chunk of content can be a template. This is great if you need to wrap data in HTML (as in for a mass email). The best part about this is that your "template" can now be stored in a database, instead of just in the file system.

  • template
  • templating
Read More

Template tag for stripping blank lines

When writing clean and easy-to-read templates, it's usually good to have structural template tags (e.g. {%for%}, {%if%}) alone on their own line with proper indentation. When such a template is rendered, the resulting HTML will have blank lines in place of the template tags. The leading blank space used for indentation is also intact. This template tag strips all empty and all-whitespace lines when rendering the template. Be careful not to apply it when not intended, e.g. when empty lines are wanted inside PRE tags.

  • template
  • html
  • strip
  • empty
  • blank
Read More

really spaceless (trim spaces at line start)

This tag is meant to override the current implementation of '{% spaceless %}' tag and remove spaces at the beginning of a line too. I.e. a template like this: <div> <div>useless space up front</div> </div> will become this `<div>` `<div>useless space up front</div>` `</div>` All the other behaviour of spaceless stays the same! Put this in your app/name/templatetags/tags.py And if you want it to override the default "spaceless"-tag to the following from django.template import add_to_builtins add_to_builtins('app.name.templatetags.tags')

  • template
  • tag
  • trim
  • spaceless
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

Capture template output as a variable

Tags like `url` and `trans` provide no way to get the result as a context variable. But how would you get a computed URL into a `blocktrans`? This snippet solves the general problem. Just put the template code whose output you want to capture within `captureas` tags. For example: {% captureas login_url %}{% url login %}{% endcaptureas %} {% blocktrans %} <a href="{{login_url}}">login</a> {%endblocktrans%}

  • template
  • variable
  • assign
  • capture
  • blocktrans
Read More

Pad integers with leading zeros (template filter)

Disclaimer: I'm not the world's greatest programmer, so there may be better ways to do this, but it works for me (feel free to offer your improvements, though!). Basically, this will pad an integer with leading zeros and return a string representation. User it like this: {% forloop.counter|leading_zeros:"5" %} ...where "5" is the number of desired digits. In this case, if it was the 12th time through the forloop, the filter would return "00012". Why do this? Either for alignment, such as in tables, or for aesthetics -- for an example, see [Shaun Inman's comment section](http://shauninman.com/archive/2007/11/16/mobilesafari_view_source).

  • template
  • filter
Read More

262 snippets posted so far.