Search code examples
web2pyweb2py-modules

Using modules in views


How can I use modules in views? For example I'm trying to use the markdown module, so I import it into my controller:

from gluon.contrib.markdown.markdown2 import markdown

and I use response.render

return response.render('default/main.html', locals())

but when I try to access it in a view,

{{=markdown(post.message)}}

I get an error saying that it is not defined:

<type 'exceptions.NameError'> name 'markdown' is not defined

How can I pass module to views? Is there an alternative to the locals() function to get it done?

On a side note, I can access db and session from my views, is this because they are imported in my models?

Web2Py Version 1.99.7 (2012-03-04 22:12:08) stable

UPDATE: Importing it in my model db.py seems to fix it. Is there a better way to do this?


Solution

  • Just for record.

    It is not a good idea to use locals()

    instead of passing locals to response.render, it is better to create a dictionary with the keys you want to be available for the view to be rendered.

    You can also include a reference to markdown on that dictionary

    from gluon.contrib.markdown.markdown2 import markdown
    mydict = dict(markdown=markdown, anotherkey=anothervalue)
    return response.render("path/to/view", mydict)
    

    Dont try to extend locals() in to mydict, you will run in to problems if you try this.

    Also you can just use the default web2py behavior

    from gluon.contrib.markdown.markdown2 import markdown
    response.view = "path/to/view"
    return dict(markdown=markdown, anotherkey=anothervalue)
    

    another option for you is to import markdown in a model file.