Login

static tag

Author:
KpoH
Posted:
November 28, 2008
Language:
Python
Version:
1.0
Score:
1 (after 3 ratings)

Django template tag for easy static files linking into your html.

See docstring for documentation.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# -*- coding: utf-8 -*-
import string

from django import template
from django.conf import settings
from django.template import resolve_variable


register = template.Library()

class MenuNode(template.Node):
    def __init__(self, file_path, params):
        self.file_path = file_path
        self.params = params

    def render(self, context):
        self.file_path = resolve_variable(self.file_path, context)
        if not self.file_path.startswith('/'):
            self.file_path = settings.MEDIA_URL+self.file_path
        file_type = self.file_path.split('.')[-1:][0].lower()
        params = {'file_path': self.file_path}
        if file_type == 'css':
            tpl = string.Template('<link href="$file_path" rel="stylesheet" type="text/css" media="$optimal" />')
            try:
                params['optimal'] = self.params[:1][0] or u'screen'
            except IndexError:
                params['optimal'] = u'screen'
        elif file_type == 'js':
            tpl = string.Template('<script type="text/javascript" src="$file_path"></script>')
        elif file_type in ['png', 'jpg', 'jpeg', 'gif']:
            tpl = string.Template('<img src="$file_path" alt="$alt" title="$alt" $optional/>')
            try:
                params['alt'] = self.params[:1][0]
            except IndexError:
                template.TemplateSyntaxError, 'static tag using for images require ALT text parameter'
            try:
                #params['optional'] = self.params[1:][0]
                dim = self.params[1:][0].split('x')
                params['optional'] = 'width="%s" height="%s"' % (dim[0], dim[1])
            except IndexError:
                params['optional'] = u''
        return tpl.substitute(**params)

@register.tag
def static(parser, token):
    """
    {% static file_name_from_context [media] %} -> 
        <link href="/some/file_name/from_context.css" rel="stylesheet" type="text/css" media="[media]" />

    {% static "css/styles.css" [media] %} -> 
        <link href="{{ MEDIA_URL }}css/styles.css" rel="stylesheet" type="text/css" media="[media]" />

    {% static "/css/styles.css" [media] %} -> 
        <link href="/css/styles.css" rel="stylesheet" type="text/css" media="[media]" />
    
    {% static "js/script.js" %} -> 
        <script type="text/javascript" src="{{ MEDIA_URL }}js/script.js"></script>
    
    {% static "img/image.(png|jpg|jpeg|gif)" "alt" [[H]x[W]] %} -> 
        <img src="{{ MEDIA_URL }}img/image.(png|jpg|jpeg|gif)" alt="alt" title="alt" [height="H" width="W"] />

    """
    bits = token.split_contents()
    tag = bits.pop(0)
    try:
        file_path = bits.pop(0)
    except IndexError:
        raise template.TemplateSyntaxError, "%r tag requires at least one param" % tag
    return MenuNode(file_path, bits)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.