Using inheritance to eliminate template logic
Filed under: turbostan templateI recently added a logic tag to TurboStan with some mixed feelings. One of the things I love about using TurboStan is that I'm constantly discovering new ways to utilize its features.
I'm working on a couple of sites that will have one-off pages, that is, pages that don't fit the standard template for the site. In this case, the only difference was that the home page would not have a sidebar, but the other pages all would. In all cases, index.stan defined the overall site layout, and public.stan filled in slots in this template.
The quick and easy solution seemed to be to use the new "case" tag something like this:
#index.stan
html [
body [
div ( id = 'left-sidebar' ) [ slot ( 'left-sidebar' ) ],
div ( id = 'content' ) [ slot ( 'content' ) ]
]
]
#public.stan
inherits ( 'index' ) [
override ( 'left-sidebar' ) [
case ( vars.page != '/home' ) [
xml ( 'left sidebar stuff!' )
]
],
override ( 'content' ) [
div ( render = vars.content, data = vars.page )
]
]
This worked fine, except I had a problem: even though the left-sidebar was now empty on the /home page, the CSS attached to it was still in effect. "Easy", I thought, "I'll move the div inside the case tag. So now I ended up with something like:
#index.stan
html [
body [
slot ( 'left-sidebar' ),
slot ( 'content' )
]
]
#public.stan
inherits ( 'index' ) [
override ( 'left-sidebar' ) [
case ( vars.page != '/home' ) [
div ( id = 'left-sidebar' ) [
xml ( 'left sidebar stuff!' )
]
]
],
override ( 'content' ) [
div ( id='content', render = vars.content, data = vars.page )
]
]
This was looking better. I could see how this small alteration gave me a bit more flexibility. However, I still had a problem: in order to make the left-column and content divs sit side-by-side, I was forced to give them both fixed widths in the CSS. If I removed the widths, the content div ended up underneath the left sidebar. The problem was that the /home page needed to be wider than this.
Anyway, I tossed out several ideas that seemed like kludges until it finally dawned on me: inheritance was the answer. I added a new template home.stan, a new controller that utilized that template, and ended up with the following:
#index.stan
html [
body [
slot ( 'left-sidebar' ),
slot ( 'content' )
]
]
#public.stan
inherits ( 'index' ) [
override ( 'left-sidebar' ) [
div ( id = 'left-sidebar' ) [
xml ( 'left sidebar stuff!' )
]
],
override ( 'content' ) [
div ( id='content', render = vars.content, data = vars.page )
]
]
#home.stan
inherits ( 'public' ) [
override ( 'left-sidebar' ),
override ( 'content' ) [
div ( id = 'home', render = vars.content, data = vars.page )
]
]
Much better! Now not only had I removed the need for actual logic in the template, but I was able to have a separate id for the home page which allowed me to set the width for content div to a different value than the rest of the site.





