Template filter used in cloud plugin
[myslice.git] / portal / templatetags / portal_filters.py
1 from django import template
2 from django.template.loader_tags import do_include
3 from django.core.files.storage import default_storage
4 from myslice.settings import theme
5
6 register = template.Library()
7
8 class IncludeNode(template.Node):
9     
10     def __init__(self, template_name):
11         if theme :
12             self.theme_template_name = "%s%s" % (theme, template_name)
13         self.template_name = template_name
14
15     def render(self, context):
16         try:
17             # Loading the template and rendering it
18             included_template = template.loader.get_template(self.theme_template_name).render(context)
19         except template.TemplateDoesNotExist:
20             # template theme does not exists, try the generic one
21             try:
22                 # Loading the template and rendering it
23                 included_template = template.loader.get_template(self.template_name).render(context)
24             except template.TemplateDoesNotExist:
25                 included_template = ''
26                 
27         return included_template
28
29 @register.tag
30 def widget(parser, token):
31     """Usage: {% widget "widget.html" %}
32
33     This will fail silently if the template doesn't exist. If it does, it will
34     be rendered with the current context."""
35     try:
36         tag_name, template_name = token.split_contents()
37     except ValueError:
38         raise template.TemplateSyntaxError, \
39             "%r tag requires a single argument" % token.contents.split()[0]
40
41     return IncludeNode(template_name[1:-1])
42
43 @register.filter(name='file_exists')
44 def file_exists(filepath):
45     if default_storage.exists('portal' + filepath):
46         return filepath
47     else:
48         index = filepath.rfind('/')
49         new_filepath = filepath[:index] + '/image.png'
50         return new_filepath
51
52 @register.filter
53 def get_type(value):
54     return type(value).__name__
55
56 @register.filter
57 def get_name_from_urn(value):
58     return value.split("+")[-1]