[Zope] Re: Help with ZPT and dynamic javascript

Josef Meile jmeile at hotmail.com
Thu Aug 12 11:18:40 EDT 2004


--- In zope at yahoogroups.com, Stephen Nesbitt <snesbitt at c...> wrote:
 > All:
 >
 > Here's my design problem - I have a form with two drop down menus.
 > The values of the second drop down depend on what the user selected
 > in the first. The values of both fields are dynamic - pulled from a
 > database when the form is published.
 >
 > I am trying to figure out how to enable this using Page Templates.
 > My thoughts are:
 > 2) use a python script and tal:replace to generate the script
 > element. This isn't working either - my suspicion is that the page
 > never processes the created script element.
I've done this before and had worked. You have to create a python script 
at the same level or on the acquisition path of your template:

   script id: myScript

   script=\
   """
     <script language="javascript" type="text/javascript">
       //Your javascript comes here
       function someFunction(someParameters){
         //line1
         //line2
         //line3
       }
     </script>
   """
   return script

Then called it from the template like:
<script language="javascript" type="text/javascript"
         tal:replace="structure here/script">
   //Some javascript
</script>

It should work.


 >
 > 3) call the database directly with javascript. I have no idea how to
 > do this or if it can be done and I really don't want to do it this
 > way.
If you want to put external data on your script, then you could do a 
query to the database and store the result on a list or a dictionary, 
then, create the javascript arrays with the data. Something like:

externalData=your_database_query_method(yourParameters)
result=['<script language="javascript" type="text/javascript">\n']
result.append('  var dataArray=new Array(')
i=0
for element in externalData:
   result.append('"%s", ' % element)
   i+=1
#Deletes the last comma
result[i]=result[i][:-2]
result.append(');\n')
script=\
"""
   //Your javascript comes here
   function someFunction(someParameters){
     //line1
     //line2
     //line3
     //Here you can access dataArray[i]
   }
</script>
"""
result.append(script)
return ''.join(result)

Call it like on the first example. Then you will get something like:

<script language="javascript" type="text/javascript">
   var dataArray=new Array("elem1", "elem2", "elem3");
   //Your javascript comes here
   function someFunction(someParameters){
     //line1
     //line2
     //line3
     //Here you can access dataArray[i]
   }
</script>

The function must be called on the handler onchange of your combobox as 
you would do it normally on html.

Regards,
Josef


More information about the Zope mailing list