Login

Snippets by durka

Snippet List

RPN template math

Django's templates don't provide much in the way of arithmetic: there is an "add" filter and that is about it. Even if sub, mult and div filters are implemented, it is difficult to chain filters while preserving some complicated expression, such as ((x+3)4-(2-y)/12.75). However, this expression can be converted into Reverse Polish Notation: x 3 + 4 * 2 y - 12.75 / - which is just a sequence of operations (push-value or apply-operator) and can be chained. To use these filters, first create a new stack for the expression with name|stnew (pass it some locally unique value). To push a number (or template variable) onto the stack, call name|stpush:number (note that you have to tell stpush the name of the stack to push onto). To pop, call name|stpop. To perform an operation, call name|st[add,sub,mult,div,mod]:number. All numbers are integers if they look like integers, or floats otherwise (integers are turned into floats upon division if they need to be). All of these functions return the name of the stack so that they can be chained. When the calculation is finished (i.e. the answer is at the bottom of the stack) call name|stget to retrieve it. Example (this was used to calculate an inline CSS value: `left: {{ forloop.counter|stnew|stpush:res.stwkday|stpush:"9.35"|stmult|stpush:res.get_item_left|stpush:"2.75"|stadd|stadd|stget }}em;`

  • template
  • filter
  • math
  • arithmetic
  • rpn
  • reverse-polish-notation
Read More

durka has posted 1 snippet.