Can I include partial view in Web2Py, passing specific variables into it?

柔情痞子 提交于 2019-12-12 09:47:36

问题


I sometimes need to use partial views in Web2Py, but I need to pass some specific variables to them. In Django it would look like this:

{% include "image.html" with caption="Me" source="http://example.com/img.png" %}

In case of Web2Py I can do something like:

{{ include "image.html" }}

but there is not even a single mention about passing variables to partial views within the documentation (or I am missing something pretty obvious).

The use case for this is decreasing complexity of the views (and implementing DRY rule) and displaying some complex content within a loop (eg. images, complex containers etc.).

I do not want to use my own tags/functions instead - I need something quick and simple, just to include partial view with specific variables. Similarly as it could be done in Django or many other web frameworks. Is it even possible, or due to Web2Py's architecture it is rather impossible / laborous?

Please tell me if this is possible in web2py or if I should rather create my own tag to use it within views (if so, what is the easiest/simplest way to do it?).

Thanks.


回答1:


Interrobang's answer is correct -- variables returned by the controller will be available even in included (as well as extended) views. So, you can do:

In mycontroller.py:

def myfunc():
    return dict(caption='Me', source='http://example.com/img.png')

and then in /views/mycontroller/myfunc.html:

{{include 'image.html'}}

In that case, caption and source will be available in the image.html view. Instead of returning caption and source from the controller, another option is just to define them in the view before the include directive:

{{caption = 'Me'
  source = 'http://example.com/img.png'}}
{{include 'image.html'}}



回答2:


From the book:

It is also worth pointing out that the variables returned by the controller function are available not only in the function's main view, but in all of its extended and included views as well.

Unless I'm misunderstanding your question, you don't have to specifically pass the variables-- instead, just use them as normal.




回答3:


To elaborate on Anthony's answer, If you need additional variables passed to the view, just include them in the return dict. In my current project I pass a whole bunch of variables to be used in the view.

return dict(maxsize=5, message='hello world', fadetimeout=10, warning=0)

Also if you need to access certain values in multiple views in your web, you could store them in the session.

session.some_var_i_need_in_multiple_views = ['one', 'two', 'three']

Then access it in the view:

{{=H3(session.some_var_i_need_in_multiple_views[0])}}


来源:https://stackoverflow.com/questions/9674630/can-i-include-partial-view-in-web2py-passing-specific-variables-into-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!