👋
I'm trying to come up with a way build an HTML template in the cleanest way possible.
I can do:
import htmlgen
proc layout(view: string): string =
result =
head(link(rel="stylesheet", href="styles.css")) &
h1("In time") &
p("you will know the ") &
view &
p("extent of my failings")
echo layout p("tragic")
which will result in
<head><link rel="stylesheet" href="styles.css" /></head>
<h1>In time</h1>
<p>you will know the </p>
<p>tragic</p>
<p>extent of my failings</p>
However, I'd much rather have something like:
proc layout(view: string): string =
result =
head link(rel="stylesheet", href="styles.css") &
h1 "In time" &
p "you will know the " &
view &
p "extent of my failings"
but that produces
<head>
<link rel="stylesheet" href="styles.css" />
<h1>In time
<p>you will know the
<p>tragic</p>
<p>extent of my failings
</p></p></h1></head>
1 Is there way to make the second syntax viable? Is there maybe a macro-terminating character which at least would allow something like:
head link(rel="stylesheet", href="styles.css") | &
h1 "In time" | &
p "you will know the " | &
2 Building the string with &s seems a little weird, but it's ok I guess. Is there a better way out of the box?
3 For containment, currently I need to do something like:
div(p "you will know the ")
can someone please tell me, how could I make it so that I can use indentation for that? Like:
div
p "you will know the "
Much appreciated!
PS: I know about Karax, but I'd rather not import a big lib like that.
I know about Karax, but I'd rather not import a big lib like that.
Karax is not big and Nim optimizes away what you don't use.
You can easly make your own HTML lib with templates:
var htmlStr = ""
template tag(name: string, body: untyped) =
htmlStr.add "<" & name & ">"
body
htmlStr.add "</" & name & ">"
template tagParams(name: string, body: untyped) =
htmlStr.add "<" & name
body
htmlStr.add ">"
template html(body: untyped) = tag("html", body)
template head(body: untyped) = tag("head", body)
template body(body: untyped) = tag("body", body)
template area(body: untyped) = tag("area", body)
template link(rel, href: string) =
tagParams "link":
htmlStr.add "rel=\"" & rel & "\" "
htmlStr.add "href=\"" & href & "\""
template h1(text: string) =
tag "h1":
htmlStr.add text
template p(text: string) =
tag "p":
htmlStr.add text
html:
head:
link(rel="stylesheet", href="styles.css")
body:
area:
h1 "In time"
p "you will know the "
p "extent of my failings"
echo htmlStr
outout:
<html><head><linkrel="stylesheet" href="styles.css"></head><body><area><h1>In time</h1><p>you will know the </p><p>extent of my failings</p></area></body></html>