malgorithms / toffee

a NodeJS and browser templating language based on coffeescript, with the slickest syntax ever
MIT License
174 stars 10 forks source link

Does Toffee support inheritance? #28

Open leeola opened 10 years ago

leeola commented 10 years ago

I'm looking for a way to wrap another template around the current template, something like inheritance. Is there any way to do this in Toffee?

malgorithms commented 10 years ago

Not really the way you'd like. There are a few ways to wrap one template around another, but none of them are done by declaring at the top of one template to include itself in another.

Solution 1: some file which coordinates this

partial is just a function which returns a string, which normally you print. But you could assign its output to a var and pass it to another file.

So for example, to make child.toffee go inside parent.toffee as a var, you could do something like this (outside of both of those files):

<h1>This is interesting</h1>
#{partial 'parent.toffee', {content: partial 'child.toffee'}}

Inside parent.toffee you'd print it like so:

<!-- raw because you don't want to escape the HTML you pubbed -->
#{raw content} 

Solution 2: a top-down approach.

Rather than starting with the child and declaring a parent, you can always tell the parent which child to use. Sort of reverse inheritance. This is typically how I would do it, although it requires the parent is aware of the children:

<!-- assuming you've passed a 'language' var -->
<h1>I am the parent doc</h1>
#{partial "./children/#{language}.toffee}

So you can always just publish a parent file and tell which inheritance you want from it.

I typically would do something like solution 2, personally. Imagine I had a general type of template called 'user-list' but specifically I wanted to show a list of people who were admins, so there was more info, I would just publish user-list.toffee but pass a var saying that it was an admin list, and it could include different sub files.

Again, neither of these solutions is probably what you're looking for, exactly.