Core Functions - Render HTML

The core module contains the html function which renders HTML from data structure. All strings are escaped by default; to prevent a string to be escaped, use the raw function.

Syntax Reminder

=> (html ['p])
"<p><p/>"
=> (html ['p "some text"])
"<p>some text</p>"
=> (html ['p {'attr "an-attr"} "some text"])
"<p attr="an-attr">some text</p>"
=> (html ['p {'attr "an-attr"}
            ['div "lorem"]
            ['div "ipsum"]])
"<p attr="an-attr">
  <div>lorem</div>
  <div>ipsum</div>
</p>"
=> (html ['p {'attr "an-attr"}
            *[['div "lorem"]
              ['div "ipsum"]]])
"<p attr=\"an-attr\">
  <div>lorem</div>
  <div>ipsum</div>
</p>"
=> (html ['p {'attr "an-attr"}
            (iter [['div "lorem"]
                   ['div "ipsum"]])])
"<p attr=\"an-attr\">
  <div>lorem</div>
  <div>ipsum</div>
</p>"
>>> html(['p'])
'<p></p>'
>>> html(['p', 'some text'])
'<p>some text</p>'
>>> html(['p', {'attr': 'an-attr'}, 'some text'])
'<p attr="an-attr">some text</p>'
>>> html(['p', {'attr': 'an-attr'},
          ['div', 'lorem'],
          ['div', 'ipsum']])
'<p attr="an-attr">
  <div>lorem</div>
  <div>ipsum</div>
</p>'
>>> html(['p', {'attr': 'an-attr'},
          *[['div', 'lorem'],
            ['div', 'ipsum']]])
'<p attr="an-attr">
  <div>lorem</div>
  <div>ipsum</div>
</p>'
>>> html(['p', {'attr': 'an-attr'},
          iter([['div', 'lorem'],
                ['div', 'ipsum']])])
'<p attr="an-attr">
  <div>lorem</div>
  <div>ipsum</div>
</p>'

String Escaping

By default, html escapes all strings. This behaviour can be customized with escape-strings parameter:

=> (setv content ['p "line<br>other"])
=> (html content :escape-strings False)
"<p>line<br>other</p>"
>>> content = ['p', 'line<br>other']
>>> html(content, escape_strings=False)
'<p>line<br>other</p>'

raw function can be used to prevent a single expression to be escaped:

=> (setv content ['p (raw "line<br>other")])
=> (html content)
"<p>line<br>other</p>"
>>> content = ['p', raw('line<br>other')]
>>> html(content)
'<p>line<br>other</p>'

Note that html returns a raw string:

=> (setv content (html ['p "some text"]))
=> (html ['div content])
"<div><p>some text</p></div>"
>>> content = html(['p', 'some text'])
>>> html(['div', content])
'<div><p>some text</p></div>'

API

Source code: hyccup/core.hy

(hyccup.core.html #* content *  [mode xhtml]  [escape-strings True])

Compile data structure into an HTML raw string.

RawStr is a subclass of str, so it can be manipulated just like a string.

Parameters
  • *content – One or more lists representing HTML to render.

  • mode – The HTML mode: "html" / "xml" / "xhtml" (default).

  • escape-strings – Boolean indicating if strings must be escaped (default: True).

Return type

hyccup.util.RawStr

(hyccup.core.raw obj)

Produce a raw string from obj.

Raw strings are not escaped. If obj is a collection, concatenate the string representation of the contained elements.

Return type

hyccup.util.RawStr