Unnamed::Template

J

John W. Long

I've been working on a yet-to-be-named templating system similar to in
fashion to textpattern's (http://textpattern.org).

--

#Currently you can define a template:

template = <<-TEMPLATE
<jwl:cart>
<ul>
<jwl:item limit="5">
<li><jwl:name /> <jwl:price /></li>
</txp:item>
</ul>
Total: <jwl:total />
</jwl:cart>
TEMPLATE

#Define a Context class:

class CartContext < Template::Context
def initalize
@cart = Shopping::Cart.new
@item = nil
end

def cart(attr)
yield
end

def item(attr)
result = ""
@cart.items.each_with_index do |item, index|
@item = item
result << yield
break unless attr["limit"] && (index < attr["limit"](
end
result
end

def name(attr)
@item.name if @item
end

def price(attr)
@item.price if @item
end

def total(attr)
@cart.total
end
end

#Then merge context with template for the expected results:

parser = Template::parser.new( :pre => "jwl", :context => CartContext )
puts parser.parse(template)

--

I would like to work out a way to force tags to comply to a certain
hierarchy. In this instance, you shouldn't be able to use the "item" tag
out side of a "cart", or "name" or "price" out side of "item".

My current thought is to use a couple of class methods to make this work:

--

my_context = Context.new do
tag "cart" do
tag "item" do
tag "name"
def name(attr)
@item.name if @item
end
tag "price"
def price(attr)
@item.price if @item
end
end
def item(attr)
result = ""
@cart.items.each_with_index do |item, index|
@item = item
result << yield
break unless index < attr["limit"]
end
result
end
end
def cart(attr)
yeild
end
end

--

The flaw of this implementation is that there is a fair amount of
duplication. Does anybody have a better idea for a pseudo language for
defining tag heirarchy?

You can find a version of the project attached to this message:

http://rubyforge.org/pipermail/chicagogroup-members-list/2005-January/000039.html
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,197
Latest member
ScottChare

Latest Threads

Top