Login

Tag "templates"

Snippet List

Template class to test custom tag libraries

TestableTemplate behaves just like django.template.Template, but you can give it a list of template.Libraries to load before parsing the template. This is equivalent to adding a bunch of {% load %} tags to the beginning of your template string, but you can use custom tag libraries which do not belong to Django applications' templatetags packages. This is occasionally useful in testing.

  • templates
Read More

testdata tag for templates

The "testdata" tag allows you to inline test data into your templates, similar in spirit to Python doctests. There are two sections--the test data and the actual template to be rendered. In non-test mode your template renders normally from whatever views call it, and there is very little overhead to skip over the test data section (happens at parse time). Here are the goals: 1. Provide convenient way to test templates without surrounding infrastructure. 2. Make templates be self-documenting in terms of expected data. 3. Allow insertion of test data at arbitrary places in template structure. Hello-world looks like this: {% load handytags %} {% testdata %} { 'greeting': 'Hello', 'planet': 'World', } {% --- %} {# This is where the actual template begins #} {{ greeting }} <b>{{ planet }}</b> {% endtestdata %} To invoke it, set up urls.py with something like this: url(r'^testdata/(?P<template_path>.*)', test_template) def test_template(request, template_path): context = {'testdata_use': True} # put request vars into context to help choose # which test data we want to render for field in request.GET: context[field] = request.GET[field] return render_with_request(template_path, context, request) Then call: http://127.0.0.1:8000/testdata/hello_world.html Features: 1. The testdata tag's rendering will expose missing variables a bit more aggressively than Django normally does. 2. You have the full power of the template language to set the test data (which ultimately gets eval'ed as a Python expression). 3. As mentioned above, the tag is mostly unobtrusive. Limitations/caveats: 1. Right now the only data format I support is pure Python, but the tag could be modified pretty easily to support JSON or YAML. 2. The VerboseContext class is pretty heavy-handed--I really just want a hook into Django to tell it to render a section with more strictness about variables. Suggestions welcome. 3. You can put the testdata tag pretty much anywhere, but the normal rules apply...for example, if you are in a template that has the extend tag, you'll want to put the testdata tag in individual blocks.

  • templates
  • testing
  • doctest
  • custom-template-tag
Read More

mini_render_to_response

You need the mini-detector middleware installed [http://www.iterasi.net/openviewer.aspx?sqrlitid=-e2dfig9w0yrclxaigp-uw](http://www.iterasi.net/openviewer.aspx?sqrlitid=-e2dfig9w0yrclxaigp-uw). This is a drop in replacement to render_to_response. When using mini_render_to_response it will try to load a version of your template with &#157;mini at the end. For example "home_mini.html" instead of "home.html". If it doesn't find the _mini version it falls back to the regular "home.html" version of your template. Easy way to maintain a "small screen" version of your templates for iPhone or other small screen devices.

  • templates
  • render
  • iphone
  • mini
Read More

monkey-patch django to use jinja2 templates for 404/500 pages and 3rd-party apps

This is heavily inspired by [http://code.google.com/p/smorgasbord/](http://code.google.com/p/smorgasbord/). But that couldn't reuse an existing jinja2 Environment, nor set filters on the Environment it created. This code assumes that you have `env` declared previously in the file as your Jinja2 Environment instance. In `settings.py`, you should set KEEP_DJANGO_TEMPLATES = ( '/django/contrib/', ) so that your Django admin still works. You can also set any other places that you do want to use Django templates there.

  • templates
  • jinja2
Read More

"Partial Templates" - an alternative to "include"

This snippet adds simple partial support to your templates. You can pass data to the partial, and use it as you would in a regular template. It is different from Django's `{% include %}`, because it allows you to pass a custom variable (context), instead of reusing the same context for the included template. This decouples the templates from each other and allows for their greater reuse. The attached code needs to go into `templatetags` folder underneath your project. The usage is pretty simple - `{% load ... %}` the tag library, and use `{% partial_template template-name data %}` in your template. This will result in template passed as **template-name** to be loaded from **partials** folder. The **.html** extension will be appended to the file name. The file has to be in one of template paths accessible to the loader) and rendered with **data** as its context. The data is available in the template as an `item` context variable. You can find more information in the [relevant Django documentation](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#howto-custom-template-tags)

  • template
  • tag
  • templates
  • tags
  • partial
  • include
  • partials
Read More

Jinja2 integration + application specific functions/filters/tests

Jinja2 is an alternative template system that can be plugged into django. It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2 (The syntax is very similar). In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too! The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests. If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps. This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically. Here's how to use this: 1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH) 2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory) 3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )` 4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)

  • template
  • templates
  • jinja
  • template-tags
  • jinja2
Read More

Jinja2 Django integration

Integration of django and Jinja2. Just import render_to_response from this file and you are ready. This file automatically adds template search path from yout TEMPLATE_DIRS and from each installed application. You can also use several variables in your settings.py to add filters, tests and global functions to the default context. This can be done by using JINJA_GLOBALS, JINJA_FILTERS and JINJA_TEST e.g. `JINJA_FILTERS = ( 'myapp.filters.myfilter', 'myapp.filters.myfilter2', )`

  • templates
  • jinja
  • jinja2
Read More

Render specific blocks from templates (useful for AJAX, alternative)

Special thanks to the author of snippet 769 who provided most of the code for this snippet. Major differences: 1.Simpler/better handling of "extends" block tag 2.Searches If/Else blocks 3.Less code 4.Allow list of templates to be passed which is closer to the behavior of render_to_response

  • template
  • block
  • templates
  • render
  • context
  • blocks
Read More

Render specific blocks from templates (useful for AJAX)

Allows getting the rendered content of a specific block tag. Useful if you want to send just a part of a template back for an AJAX request. Works for arbitrary template inheritance, even if a block is defined in the child template but not in the parent. Example: In `test1.html`: {% block block1 %}block1 from test1{% endblock %} {% block block2 %}block2 from test1{% endblock %} In `test2.html`: {% extends 'test1.html' %} {% block block1 %}block1 from test1{% endblock %} And from the Python shell: >>> from django.template import loader, Context >>> from template import render_block_to_string >>> print render_block_to_string('test2.html', 'block1', Context({})) u'block1 from test2' >>> print render_block_to_string('test2.html', 'block2', Context({})) u'block2 from test1' UPDATE: See also [zbyte64](http://www.djangosnippets.org/users/zbyte64/)'s implementation in snippet [#942](http://www.djangosnippets.org/snippets/942/)

  • template
  • block
  • templates
  • render
  • context
  • blocks
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

Form row filter

I love newforms. But sometimes using ``{{ form }}`` within a template doesn't give you enough flexibility. The other option, manually defining the markup for each field, is tedious, boring and error-prone. This is an example of how you can use a template filter to get the best of both worlds. Use it like this to render an entire form: ``{% for field in form %}`` {{ field|form_row }} ``{% endfor %}`` Or use it on a per-field basis: ``<fieldset>`` {{ form.first_name|form_row }} {{ form.last_name|form_row }} ``</fieldset>``

  • newforms
  • forms
  • templates
  • filters
Read More

Foldable Admin Interface

Have you had a rather huge database, say 50-100+ tables? Why not compress the tables you don't want to see and expand the ones that you do want to see? This template should do the trick. It uses cookies to remember which tabs you have open and which ones you have closed. This should work on .91 to current. How to install - just CP code and save as index.html toss in your media folder under /path_to_media/template_folder/admin/index.html. next download mootools and toss this into /path_to_media/js_folder/mootools.js (alternatively you could be lazy and cp mootools into the script tag of this template) A quick and dirty fix but it sure saves time trying to find the tables you are looking for.

  • django
  • admin
  • templates
  • html
Read More

sublist

*Usage:* `list|sublist:"a:b"` Returns `list[a:b]` Accepts `":b"` and `"a:"` shortcuts Note that the double quotes are necessary

  • filter
  • lists
  • templates
Read More

mark a required field by "*" in a template

the trick resides in `field.field.required`. The intuitive way of testing this in the templates is to access `field.required`. But it's not the good one. Enjoy! [Found via Django users Google Groups](http://groups.google.com/group/django-users/browse_thread/thread/ce83f74fb1156b4b/0df36947de16a071?lnk=gst&q=required+field#0df36947de16a071)

  • newforms
  • forms
  • templates
  • field
  • required
Read More

36 snippets posted so far.