开发者

Condition mako base template from inheriting one

开发者 https://www.devze.com 2023-01-19 16:29 出处:网络
I have a base.mako template with a if statement to inc开发者_如何学Clude or not jQuery <head>

I have a base.mako template with a if statement to inc开发者_如何学Clude or not jQuery

<head>
% if getattr(c, 'includeJQuery', False):
    <script type="text/javascript" src="jquery.js"></script>
% endif
...

Several templates inherit from base.mako, someone needs jQuery, someone don't.

At the moment I have to set the attribute in the controller before calling render

c.includeJQuery = True
return render('/jQueryTemplate.mako')

but I think this should go directly in child template (i.e. jQueryTemplate.mako)

I tried adding it before inherit

<% c.includeJQuery = True %>
<%inherit file="/base.mako"/>\ 

but it does not work.

Any tips?

Thanks for your support


You shouldn't be using "c" in your template.

<% includeJquery = True %>

and

% if includeJquery:
...
% endif

should suffice.

I think you are doing this wrong... In your base template you should make a blank def for a jquery block and call it. Then in the inherited template just redefine the block.

base.mako:

<head>
${self.jquery()}
</head>

<%def name="jquery()"></%def>

Then in another template you add jquery with:

<%inherit file="base.mako />

<%def name="jquery()">
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
</%def>


Well, since with the line

<script type="text/javascript" src="jquery.js"></script>

I also need to add some other js I put a jQueryScript %def in child template

##jQueryTemplate.mako
<%def name="jQueryScript()">
    <script>
    </script>
</%def>

then in base I check if exists and add all accordingly

#base.mako
%if hasattr(next, 'jQueryScript'):
    <script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
    ${next.jQueryScript()}
%endif

so I don't need to set nothing in the controller.

0

精彩评论

暂无评论...
验证码 换一张
取 消