Skip to content

Latest commit

 

History

History
123 lines (89 loc) · 2.35 KB

File metadata and controls

123 lines (89 loc) · 2.35 KB
description Interpolate string placeholders of the form <code v-pre>{{.

template

Interpolate string placeholders of the form {{...}}.

Usage

template = require "mods.template"

view = {
  user = { name = "Ada" },
}

out = template("Hello {{user.name}}!", view) --> "Hello Ada!"

template(tmpl, view)

Render string templates with {{...}} placeholders.

Parameters:

  • tmpl (string): Template string with placeholders.
  • view (table): Input data used to resolve placeholders.

Return:

  • out (string): Rendered output string.

Example:

view = { subject = "World" }
template("Hello {{subject}}", view) --> "Hello World"

Note

Whitespace inside placeholders is ignored.

template("Hi {{ name }}", { name = "Ada" }) --> "Hi Ada"

Dot Paths

Use dot notation to access nested values in view.

view = { user = { meta = { role = "Engineer" } } }
template("Role: {{user.meta.role}}", view) --> "Role: Engineer"

Note

{{.}} renders the entire root view table, not a nested field.

template("View: {{.}}", { value = 123 })
--> View: {
--    value = 123
--  }

Function Values

If a placeholder resolves to a function, that function is called and its result is rendered.

view = { name_func = function() return "Ada" end }
template("Hi {{name_func}}", view) --> "Hi Ada"

Note

If the function returns nil, the placeholder renders as an empty string.

Table Values

Table placeholders are rendered using mods.repr.

view = { data = { a = 1, b = true } }
template("Data: {{data}}", view)
--> Data: {
--    a = 1,
--    b = true
--  }

Missing and Invalid Placeholders

Missing keys render as an empty string.

view = {}
template("Missing: {{unknown}}", view) --> "Missing: "

Invalid placeholder names render as an empty string (for example: {{..}}, {{.name}}, {{user.}}, {{user..name}}).

view = { user = { name = "Ada" } }
template("Bad: {{user..name}}", view) --> "Bad: "

If a placeholder is not closed ({{unclosed), it is emitted as-is.

view = { name = "Ada" }
template("Hi {{name", view) --> "Hi {{name"