Search code examples
javascriptpython-2.7web2py

Extracting values out of a python list as individual entities


please someone out there coz I'm pulling out my hairs at this point: I want to extract pictures from within a list extracted from the database and store them inside a JavaScript array for a slide show. I am using a web2py framework. CONTROLLER

>`def form1Details():
  form=db.compForm(request.args(0))
  forms=db(db.compFormPages.formName==form.id).\
  select(db.compFormPages.ALL)
  return locals()

`

the images are in variable forms so i wanna display them in my view such that each picture is stored individually inside a JavaScript array for a slide show like below

VIEW

>`{{for pic in forms:}}
 <script>
function slideShow()
{
images = ["{{=URL('download',args=pic.formImage)}}",
"{{=URL('download',args=pic2.formImage)}}"],
"{{=URL('download',args=pic3.formImage)}}"];
descriptions=['{{=pic.formTitle}}',
'{{=pic2.formTitle}}',
'{{=pic2.formTitle}}';
...............
...............
</script>
}`

How do I extract them individually to achieve whats in the view above, i could use all the help i could get, thank you.


Solution

  • Assuming your goal is some Javascript code with a variable holding an array of URLs and another variable holding an array of descriptions, one simple approach is to use the ASSIGNJS helper, which will write the Javascript variables and generate their values by converting the associated Python data structures to JSON. So, in the view:

    <script>
    function slideShow() {
      {{=ASSIGNJS(images=[URL('default', 'download', args=form.formImage)
                          for form in forms],
                  descriptions=[form.formTitle for form in forms])}}
      ...
    }
    </script>
    

    That will yield Javascript like this:

    var images = ["/myapp/default/download/image1", "/myapp/default/download/image2", ...];
    var descriptions = ["Title 1", "Title 2", ...]
    

    You might also instead consider generating an array of Javascript objects containing both the URL and description for each image:

    {{=ASSIGNJS(images=[dict(url=URL('default', 'download', args=form.formImage),
                             description=form.formTitle)
                        for form in forms])}}
    

    which will yield:

    var images = [{"url": "/myapp/default/download/image1", "description": "Title 1"}, ...];