Changeset 14133


Ignore:
Timestamp:
03/15/12 16:28:38 (12 years ago)
Author:
ramonb
Message:

templatetags/cmts_extras.py:

  • added tag: assign for variable assignment
  • see #4
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sara_cmt/sara_cmt/cluster/templatetags/cmts_extras.py

    r14132 r14133  
    9595
    9696register.filter( 'ip_last_digit', ip_last_digit )
     97
     98@register.tag(name='assign')
     99def do_assign(parser,token):
     100
     101    """
     102        Variable assignment within template
     103
     104        Usage: {% assign newvar = <space seperated list of strings/vars> %}
     105         i.e.: {% assign file_name = '/var/tmp/rack-' rack.label '.txt' %}
     106    """
     107    definition = token.split_contents()
     108
     109    if len(definition) < 4:
     110        raise template.TemplateSyntaxError, '%r tag requires at least 4 arguments' % tag
     111
     112    tag = definition[0]
     113    new_var = definition[1]
     114    is_teken = definition[2]
     115    assignees = definition[3:]
     116
     117    return resolveVariables( new_var, assignees )
     118
     119class resolveVariables(template.Node):
     120
     121    def __init__(self, varname, varlist ):
     122
     123        self.varname = varname
     124        self.varlist = varlist
     125
     126    def render(self, context):
     127        resvars = [ ]
     128
     129        for a in self.varlist:
     130
     131            var_str = ''
     132
     133            if not (a[0] == a[-1] and a[0] in ('"', "'")):
     134                try:
     135                    # RB: no quotes must mean its a variable
     136                    #
     137                    a_var = template.Variable( a )
     138                    var_str = a_var.resolve(context)
     139
     140                except template.VariableDoesNotExist:
     141
     142                    #RB: still think not allowed to raise exceptions from render function
     143                    #
     144                    #raise template.TemplateSyntaxError, 'cannot resolve variable %r' %(  str( self.path ) )
     145                    pass
     146
     147                resvars.append( str(var_str) )
     148
     149            else:
     150                #RB: assume strings are quoted
     151                #RB: strip quotes from string
     152                #
     153                a = str( a.strip("'").strip('"') )
     154                resvars.append( str(a) )
     155
     156        #RB: finally assign the concatenated string to new varname
     157        context[ self.varname ] = string.join( resvars, '' )
     158
     159        #RB: Django render functions not supposed/allowed to raise Exception, I think
     160        return ''
    97161
    98162class MetaNode(template.Node):
Note: See TracChangeset for help on using the changeset viewer.