Reputation: 1309
How can I define a variable within a Genshi template for reuse?
Let's say i have two nested for loops:
<div py:for="i in xrange(5)>
<div py:for=j in xrange(10)>
<!-- do something with "i * j" -->
<!-- do something else with "i * j" -->
<!-- do yet another thing with "i * j" -->
</div>
</div>
As indicated in the comments, I want to do a simple calculation with the two loop variables and then do something with the reslt (e.g. insert it into the template).
If possible I want to reuse the result of the calculation instead of calculating it multiple times (because the calculation might be a little bit more difficult than in the example, and also I don't want to copy the code for the calculation if I can just use a variable).
I know that one shouldn't do too many calculations in a template, but this is just an example. My goal is reusing stuff. Also I know that there is the def
tag for defining macros, but I think these just create text rather than a variable, so I can't use it for example in an if
tag for condition checking.
Is there a way to have a Python tag in a Genshi template just for simple Python expressions without having to output something?
Upvotes: -1
Views: 407
Reputation: 1693
Starting form the end: Is there a way to have a Python tag in a Genshi template just for simple Python expressions without having to output something?
Yes, you can use the following tag:
<?python ... ?>
For example:
<?python
if 'condition':
var = 'controls'
else:
var = 'controls row-fluid'
?>
and then:
<-- now class='controls' if 'condition' is true else class='controls row-fluid' -->
<div class="$var">
<-- put something inside -->
</div>
I hope it helps, if something is unclear or 'weird' please comment.
Upvotes: 1