Long story short:
* Django lets you call functions in templates, but you can't pass any parameters.
* Sometimes you need to use the request object to perform certain tasks, such as determining whether the current user has permission to do something.
* The recommended approach is to call functions that require parameters in the view, and then pass the results as variables in the context. This sometimes feels a bit overkill.
* Creating a templatetag to call any function with any parameter will definitely break the intention for not letting functions to be called with parameters in templates.
* So, what if we could tell django to inject the request into certain functions? That's what this decorator is for.
For instance, suppose you have a model:
class SomeModel(models.Model):
...
def current_user_can_do_something(self, request):
...some logic here using request...
You could use the decorator like this:
class SomeModel(models.Model):
...
@inject_request
def current_user_can_do_something(self, request=None):
...some logic here using request...
And in the template go straight to:
{{ somemodel_instance.current_user_can_do_something }}
So that the decorator would perform some operations to find the request in the frame tree and inject it if found. The assertions are intented to make sure things will work even if the request cannot be found, so that the coder may program defensively.
Tag to correctly uppercase Greek characters with accent, copy the code in your templatetags folder in a file of your choice, load it in your templates {% load yourfile %} and use it as {% string|gruppercase %} the code works also with other languages, it won't modify anything (eg {% ukwork|gruppercase %} as it transforms only Greek characters (unless your language contains Greek characters).
Simple snippet to show the names of the templates on the page. It's a custom template loader that just prints out the name of the template at the start of the template.
To set it up, just place it in a file, for example spy.py. Then edit settings.py and add this to the start of the tuple list for TEMPLATE_LOADERS.
TEMPLATE_LOADERS = (
'appname.spy.load_template_source',
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
This was useful for me because I'm starting to use a django project that's a big on the big side and I'm trying to do a theme for it. I'm not very familiar with their templates, so these visual cues will help instead of walking through the template code.
Hope this is helpful for some one else too.
This snippet provides getting templates from the model in database.
We work with templates as usual (using as a template name value of the field **"slug"**).
You can do your own application without "TemplateTypes" model - it's added for ability to filter templates. You can use choices or remove "template_type" field and "TemplateTypes" model at all.
For ease of editing, you can connect all this to the admin interface, adding to the field "template_body" widget with syntax highlighting (I used [CodeMirror](http://codemirror.net/)).
When developing a site, I sometimes want to be able to visually reference the HTML before it's given a real context, and a view. This extra bit of code will allow you to add a directory within your templates dir, and pull any html files and subdirectories from it. I added the if statement to automatically use an index.html file if there's no file and extension at the end. You can substitute anything you like for the "html" in "(?P<base>html)". That's just passed as an argument to prepend to the template as a base directory for the templates.
This is http://djangosnippets.org/snippets/1376/ rewritten as a new class-style Loader, and slightly improved.
Allows you to reference templates like this:
app_label:some/template/name.html
This makes it possible to insert customizations at any point in a template hierarchy. For example, you could replace a block within the base admin template:
{% extends "admin:admin/base.html" %}
{% block breadcrumbs %}Custom Breadcrumbs-Style{% endblock %}
The above snippet makes all of the settings.py variables accessible in templates. Add this to the context_processors.py file inside your app directory. After that add the below line to the TEMPLATE_CONTEXT_PROCESSORS in your settings.py.
'*app_name*.context_processors.access_to_settings'
**Warning**: I'm quite sure this is **not** a best practice, but this snippet has proven being very useful to me. Handle with care. I also wonder about the impact on performance, while I didn't notice any slowdown on a very small app of mine.
Idea is to expose project settings to template request context through a context processor, and \__doc__ should be self-explanatory.
Of course, if you know a better way to achieve the purpose, please tell in the comments.
This is an enhancement of snippet [#172](http://djangosnippets.org/snippets/172/). Here I use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) — far more easier to install through pip in a virtualenv, and possibly a bit more maintained — to format and properly indent the rendered HTML from templates.
I also added a check to only tidy contents in a `DEBUG=True` environment, regarding high impact on performance while doing so in production.
Last, it's compatible with Django 1.2.x.
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 your regular template folders.
The variables are passed in a with compatiable syntax, eg.
VAR as NAME and VAR as NAME
No limitations on the number of variables passed.
The code shown implements a preprocessor for Django templates to support indentation-based syntax.
The pre-markup language is called Showell Markup. It allows you to remove lots of close tags and random punctuation. It also has a syntax for cleaning up individual lines of HTML with a pipe syntax for clearly separating content from markup. You can read the docstrings to glean the interface.
Here are examples:
>> table
>> tr
>> td
Right
>> td
Center
>> td
Left
>> div class="spinnable"
>> ul
>> li id="item1"
One
>> li id="item2"
Two
%% extends 'base.html'
%% load smartif
%% block body
%% for book in books
{{ book }}
%% if condition
Display this
%% elif condition
Display that
%% else
%% include 'other.html'
>> tr class="header_row"
Original Author | th class="first_column"
Commenters | th
Title | th
Action | th
Last words | th
By | th
When | th
>> ol class="boring_list"
One | li
Two | li
Three | li
{{ element4|join:',' }} | li
Hello World! | b | span class="greeting" ; br
Goodbye World! | i | span class="parting_words"; br
; hr
>> p class="praise"
Indentation-based syntax is so
Pythonic!
Archive LINK collection.archive referral.pk
Home LINK home.home
Friends LINK friendship.friends
Create a card LINK referrals.create
Recent changes LINK activity.recent_changes
>> FORM referrals.create
{{ form.as_p }}
{{ referral.id } | HIDDEN referral
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 }}