neurino
neurino

Reputation: 12395

Condition mako base template from inheriting one

I have a base.mako template with a if statement to include 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

Upvotes: 0

Views: 1773

Answers (2)

aryeh
aryeh

Reputation: 2215

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>

Upvotes: 3

neurino
neurino

Reputation: 12395

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.

Upvotes: 2

Related Questions