You can define subclass and override methods head and body
class MyPage
super HTMLPage
redef body do add("p").text("Hello World!")
end
HTMLPage use fluent interface so you can chain calls as:
add("div").attr("id", "mydiv").text("My Div")
html :: HTMLPage :: defaultinit
core :: Object :: class_factory
Implementation used byget_class
to create the specific class.
core :: Writable :: defaultinit
core :: Object :: defaultinit
html :: HTMLPage :: defaultinit
core :: Object :: is_same_instance
Return true ifself
and other
are the same instance (i.e. same identity).
core :: Object :: is_same_serialized
Isself
the same as other
in a serialization context?
core :: Object :: is_same_type
Return true ifself
and other
have the same dynamic type.
core :: Object :: output_class_name
Display class name on stdout (debug only).core :: Writable :: write_to_bytes
Likewrite_to
but return a new Bytes (may be quite large)
core :: Writable :: write_to_file
Likewrite_to
but take care of creating the file
core :: Writable :: write_to_string
Likewrite_to
but return a new String (may be quite large).
# 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