You are not logged in Log in Join
You are here: Home » Members » ontoprise » secrets of python dictionaries for the use in dtml

Log in
Name

Password

 

secrets of python dictionaries for the use in dtml

If you use python dictionaries in Zope - the kind of key: value - you may want to know which keys you have, which values or which items - returned in an (key, value) list.

Example

Lets say you have a dtml-method / -document included a dictionary within:
e.g.:
<dtml-call "REQUEST.set('mObjs', [])">
<dtml-call "mObjs.append({'key1': 'test', 'key2': 'atest2', 'key3':'atest3'})">
<dtml-call "mObjs.append({'key1' : 'more test', 'key2' : 'more test2', 'key3':'atest4'})">

Iterating the normal way

over the dictionary as you are used will NOT work:
<dtml-in mObjs mapping>
  <dtml-in sequence-item>
    <dtml-var sequence-item>
  </dtml-in>
</dtml-in>

You have to know the keys (here: key1, key2, key3) to get it work:
<dtml-in mObjs mapping>
  <dtml-var key1>
  <dtml-var key2>
  &dtml-key3;
</dtml-in>

But what if you don't know the keys, or the keys are variable in quantity?

And here comes the tricky part, b/c the <dtml-var sequence-key> tag will NOT work.
I have written (more than) little scripts in Python to overcome this obstacle:
The scripts take one parameter (let's say m), which is a dictionary and the one and only line of the script is:
return m.keys()
alternatively you can add scripts, that return m.values() - the values -, or m.items() - a list of (key, value) pairs.
You may call them getDictKeys, getDictValues, or getDictItems respectively. All scripts return Python lists.

Now you can extend your dtml-method / document as follows:
<dtml-in mObjs mapping prefix="pre">
  keys: <dtml-var "getDictKeys(pre_item)"><br>
  values: <dtml-var "getDictValues(pre_item)"><br>
</dtml-in>

Hint

(note: this won't work for the Sessions objects provided since Zope 2.5.x - there you have to go the way described above)

If you're using the REQUEST.form, REQUEST.cookie, or CGI environment variables you may also use

<dtml-in "REQUEST.form.items()" sort>
  <dtml-var sequence-key>:<dtml-var sequence-item><BR>
</dtml-in>


to show all form data. Use REQUEST.cookies.items() for all your cookies, and REQUEST.items() for all REQUEST variables, including CGI Environment variables. If you don't mind the format, you could use <dtml-var REQUEST> as a shortcut.

Thank you, Paul, for the hint and kamon for the information provided.

If you have questions, please do not hesitate to contact me: