PylonsHQ.

Layout: Fixed-width

Including CSS And Javascript (etc.) In A Flexible Way With Mako

Skip to end of metadata
Go to start of metadata

Including CSS and Javascript is easy with mako inheritance

Here's an example:

basepage.mak:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<% self.seen_css = set() %>
<head>
	${self.css()}
</head>

<%def name="css_link(path, media='')">
    % if path not in self.seen_css:
        <link rel="stylesheet" type="text/css" href="${path|h}" media="${media}"></link>
    % endif
    <% self.seen_scripts.add(path) %>
</%def>
 
<%def name="css()">
	${css_link('/css/main.css', 'screen')}
	${css_link('/css/navigation.css', 'screen')}
	${css_link('/css/forms-buttons.css', 'screen')}
	${css_link('/css/orders.css', 'screen')}
</%def>

css_link is a little utility method that guards against you accidentally including the same CSS file twice.

Then, if you want to add some CSS in a child template, you can override the css method like this:

child1.mak:

1
2
3
4
<%def name="css()">
    ${parent.css()}
    ${self.css_link('/css/products.css', 'screen')}
</%def>

Or if you want to have the parent's CSS come after the child's, like this:

child2.mak:

1
2
3
4
<%def name="css()">
    ${self.css_link('/css/products.css', 'screen')}
    ${parent.css()}
</%def>

This will work just as well for larger inheritance heirarchies. The same ideas can be applied just as easily to javascript.

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

Powered by Pylons - Contact Administrators