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.
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'}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With