14.9 Template
(require pollen/template) | package: pollen |
Convenience functions for templates. These are automatically imported into the eval environment when rendering with a template (see render).
14.9.1 HTML
(require pollen/template/html) | package: pollen |
Functions specific to HTML templates.
procedure
(->html xexpr-or-xexprs [ #:tag html-tag #:attrs html-attrs #:splice? splice-html?]) → string? xexpr-or-xexprs : (or/c xexpr? (listof xexpr?)) html-tag : (or/c #f txexpr-tag?) = #f html-attrs : (or/c #f txexpr-attrs?) = #f splice-html? : boolean? = #f
> (define tx '(root (script "3 > 2") "Why is 3 > 2?"))
> (xexpr->string tx) "<root><script>3 > 2</script>Why is 3 > 2?</root>"
> (->html tx) "<root><script>3 > 2</script>Why is 3 > 2?</root>"
The optional keyword arguments html-tag and html-attrs let you set the outer tag and attributes for the generated HTML. If xexpr-or-xexprs already has an outer tag or attributes, they will be replaced.
> (define tx '(root ((id "huff")) "Bunk beds"))
> (->html tx) "<root id=\"huff\">Bunk beds</root>"
> (->html tx #:tag 'div) "<div id=\"huff\">Bunk beds</div>"
> (->html tx #:attrs '((id "doback"))) "<root id=\"doback\">Bunk beds</root>"
> (->html tx #:tag 'div #:attrs '((id "doback"))) "<div id=\"doback\">Bunk beds</div>"
Whereas if xexpr-or-xexprs has no tag or attributes, they will be added. If you supply attributes without a tag, you’ll get an error.
> (define x "Drum kit")
> (->html x) "Drum kit"
> (->html x #:tag 'div) "<div>Drum kit</div>"
> (->html x #:tag 'div #:attrs '((id "doback"))) "<div id=\"doback\">Drum kit</div>"
> (->html x #:attrs '((id "doback"))) ->html: contract violation
expected: can't use attribute list without a #:tag
argument
given: #f
If the generated HTML has an outer tag, the splice-html? option will strip it off. Otherwise this option has no effect.
> (define tx '(root (p "Chicken nuggets")))
> (->html tx) "<root><p>Chicken nuggets</p></root>"
> (->html tx #:splice? #t) "<p>Chicken nuggets</p>"
> (define x "Fancy sauce")
> (->html x) "Fancy sauce"
; This next one won't do anything > (->html x #:splice? #t) "Fancy sauce"
; Adds the outer tag, but then #:splice? removes it > (->html x #:tag 'div #:attrs '((id "doback")) #:splice? #t) "Fancy sauce"
Be careful not to pass existing HTML strings into this function, because the angle brackets will be escaped. Fine if that’s what you want, but you probably don’t.
> (define tx '(p "You did " (em "what?")))
> (->html tx) "<p>You did <em>what?</em></p>"
> (->html (->html tx)) "<p>You did <em>what?</em></p>"
As the input contract suggests, this function can take either a single xexpr? or a list of xexpr?, with the expected results.