Property definitions

html $ HTMLPage :: defaultinit
# A html page
#
# You can define subclass and override methods head and body
#
# ~~~nitish
# class MyPage
#	super HTMLPage
#	redef body do add("p").text("Hello World!")
# end
# ~~~
#
# HTMLPage use fluent interface so you can chain calls as:
#
# ~~~nitish
# add("div").attr("id", "mydiv").text("My Div")
# ~~~
class HTMLPage
	super Writable

	# Define head content
	fun head do end
	# Define body content
	fun body do end

	private var root = new HTMLTag("html")
	private var current: HTMLTag = root
	private var stack = new List[HTMLTag]

	redef fun write_to(stream) do
		root.children.clear
		open("head")
		head
		close("head")
		open("body")
		body
		close("body")
		stream.write "<!DOCTYPE html>"
		root.write_to(stream)
	end

	# Add a html tag to the current element
	#
	# ~~~nitish
	# add("div").attr("id", "mydiv").text("My Div")
	# ~~~
	fun add(tag: String): HTMLTag do
		var node = new HTMLTag(tag)
		current.add(node)
		return node
	end

	# Add a raw html string
	#
	# ~~~nitish
	# add_html("<a href='#top'>top</a>")
	# ~~~
	fun add_html(html: String) do current.add(new HTMLRaw("", html))

	# Open a html tag
	#
	# ~~~nitish
	# open("ul")
	# add("li").text("item1")
	# add("li").text("item2")
	# close("ul")
	# ~~~
	fun open(tag: String): HTMLTag do
		stack.push(current)
		current = add(tag)
		return current
	end

	# Close previously opened tag
	# Ensure: tag = previous.tag
	fun close(tag: String) do
		if not tag == current.tag then
			print "Error: Trying to close '{tag}', last opened tag was '{current.tag}'."
			abort
		end
		current = stack.pop
	end
end
lib/html/html.nit:18,1--99,3