You are not logged in Log in Join
You are here: Home » Members » dean.jenkins » Creating and manipulating Python lists

Log in
Name

Password

 

Creating and manipulating Python lists

You don't need to resort to an external method to create a Python list if you don't want to.

Say you have a folder called jokes and you filled it with DTML Documents that were .. eh ... jokes.

You could call a joke as pointed out in the How-To: How to generate random content.

<dtml-var "_.whrandom.choice(jokes.objectValues(['DTML Document']))">

But ... what if you wanted to create a weighted list of jokes ... some of your jokes may be funnier than others and you may want them displayed more often!

You could use a Python external method to create a list of jokes with funnier jokes listed more often than others and choose randomly from them or you could get DTML to do it.

Give your jokes an added property called 'weight' of type 'int' and default value '1'. Change this value depending on your sense of humour (note max=1000).

Include this DTML in your page to include a random joke.

<dtml-call "REQUEST.set('jokelist',[])">
<dtml-in "jokes.objectValues(['DTML Document'])">
<dtml-in "_.range(weight)">
<dtml-call "jokelist.append(this())">
</dtml-in>
</dtml-in>

<dtml-with "_.whrandom.choice(jokelist)">
<dtml-var "this()">
</dtml-with>

How does this work?

<dtml-call "REQUEST.set('jokelist',[])">

-> set up an empty Python list called jokelist

<dtml-in "jokes.objectValues(['DTML Document'])">
...
</dtml-in>

-> for all the DTML Documents in the jokes folder

<dtml-in "_.range(weight)">
<dtml-call "jokelist.append(this())">
</dtml-in>

-> Add weight times joke instances to the list. Set up a loop and add a joke to the joke list 'weight' number of times.

<dtml-with "_.whrandom.choice(jokelist)">
<dtml-var "this()">
</dtml-with>

-> Render (tell) the joke. Note the way "this()" renders the joke instance chosen at random from the jokelist.