hiccup

repository·master·Indexed 25 days ago

https://github.com/weavejester/hiccup

A Clojure library for representing HTML using Clojure data structures, such as vectors for elements and maps for attributes. It provides a concise DSL with automatic string escaping for security, including support for CSS-style selectors for IDs and classes and the `hiccup2.core/raw` function for rendering raw HTML.

Tokens
671
Snippets
2
Records
8
Agent score
34%

What's inside hiccup

  1. Use CSS selectors for ID and Class attributes

    master

    You can use shorthand CSS-style selectors directly in the element vector to specify id and class attributes:

    • Use # to specify an id.
    • Use . to specify one or more class names.
    • These can be combined (e.g., #id.class1.class2).
  2. Use syntax sugar for objects and sequences

    master

    Hiccup provides shorthand for common data types:

    • Objects: Non-string values (like numbers) are automatically converted to strings before rendering.
    • Seqs/Lists: Sequences are automatically expanded. This is useful for iterating over collections using Clojure macros like for.
  3. Migrate from Hiccup 1 to Hiccup 2

    master

    Hiccup 2 introduces automatic string escaping to improve security.

    • Hiccup 1: Strings are NOT escaped by default. You must manually use the h function to escape unsafe characters (e.g., < or &).
    • Hiccup 2: Strings ARE escaped automatically. The html macro returns a RawString instead of a standard String to allow for safe nesting.

    Recommendation: Use Hiccup 2 for all new projects, especially those handling user-provided data. Avoid using non-core namespaces like hiccup.page when using Hiccup 2.

  4. Use Hiccup syntax to represent HTML

    master

    Hiccup uses Clojure vectors to represent HTML elements and maps for attributes.

    • The first element of the vector is the tag name.
    • The second element can optionally be a map of attributes.
    • Subsequent elements are considered the tag's body.
    • If the body is a sequence, its contents are expanded into the element.
    • Strings are automatically escaped for security.
  5. Basic Hiccup syntax for HTML elements

    master
    Hiccup uses Clojure vectors to represent HTML elements. A vector starting with a keyword represents the tag name. Values following the keyword are treated as the element's body, allowing for nesting. Strings are rendered as plain text, and adjacent strings are concatenated.
  6. Render raw HTML strings with hiccup2.core/raw

    master

    By default, Hiccup escapes all strings. To include unescaped HTML (such as for doctype declarations or pre-rendered HTML snippets), wrap the string in the hiccup2.core/raw function.

    (require '[hiccup2.core :as h])
    
    ;; Render unescaped HTML content
    (h/html [:p (h/raw "Hello <em>World</em>")])
    
    ;; Use for doctype declarations
    (h/html (h/raw "<!DOCTYPE html>") [:html {:lang "en"}])