Skip to content

Functions

ReFreezed edited this page Jul 7, 2018 · 27 revisions

Utility Functions

a()

html = a( url [, label=prettyUrl(url) ] )

Create a simple HTML <a> element.

ceil()

n = ceil( n )

Alias for math.ceil().

chooseExistingFile()

path = chooseExistingFile( pathWithoutExtension, extensions )

Return the path of an existing file with any of the specified extensions. Returns nil if no file exists.

chooseExistingImage()

path = chooseExistingImage( pathWithoutExtension )

Return the path of an existing image file with any of the specified extensions. Returns nil if no image file exists.

Short form for chooseExistingFile(pathWithoutExtension, IMAGE_EXTENSIONS).

cssPrefix()

css = cssPrefix( property, value )

Quick and dirty way of adding vendor-specific prefixes to a CSS property. Example:

local css = cssPrefix("flex", "auto")
-- css is "-ms-flex: auto; -moz-flex: auto; -webkit-flex: auto; flex: auto;"

date()

string = date( format [, time=now ] )

Alias for os.date(). (See the C docs for date format.)

entities()

html = entities( text )

Encode HTML entities, e.g. < to &lt;.

errorf()

errorf( [ level=1, ] format, ... )

Trigger an error with a formatted message.

Short form for error(F(format, ...), level).

F()

string = F( format, ... )

Alias for string.format().

fileExists()

bool = fileExists( path )

Check if a file exists in the content folder.

fileExistsInOutput()

bool = fileExistsInOutput( path [, skipRewriting=false ] )

Check if a file exists in the output folder, optionally without the usual rewriting of the path.

files()

paths = files( folder, [ onlyFilenames=false, ] filenamePattern )
paths = files( folder, [ onlyFilenames=false, ] fileExtensionArray )
paths = files( folder, [ onlyFilenames=false, ] filterFunction )

Get a list of files in a folder inside the content folder. Examples:

local function dogFilter(filename)
	if filename:find"dog" then
		return true
	end
end

local imagePaths  = files("/images", IMAGE_EXTENSIONS)
local psFilePaths = files("/resources/misc", "%.psd$")
local dogPaths    = files("/animal-files", dogFilter)

find()

item, index = find( array, attribute, value )

Get the item in the array whose attribute is value. Returns nil if no item is found.

findAll()

items = findAll( array, attribute, value )

Get all items in the array whose attribute is value.

floor()

n = floor( n )

Alias for math.floor().

formatTemplate()

template = formatTemplate( format, valueTable )

Quick and dirty formatting of a template, presumably before using generateFromTemplate(). This replaces all instances of :key: with the corresponding field from valueTable. Example:

local template = formatTemplate(
	[[
		{{
		page.title  = :title:
		page.layout = "awesome"
		}}

		My dog likes :thing:.
		Other dogs probably like :thing: too!
	]],
	{
		title = F("%q", "Timmie the Dog"), -- Remember, :title: is in the code block.
		thing = "bones",
	}
)
generateFromTemplate("dogs/info.md", template)

Also see toLua().

generatorMeta()

html = generatorMeta( [ hideVersion=false ] )

Generate HTML generator meta tag (e.g. <meta name="generator" content="LuaWebGen 1.0.0">). This tag makes it possible to track how many websites use this generator, which is cool. This should be placed in the <head> element.

getBasename()

basename = getBasename( filename )

Get the filename without the extension. Example:

local basename = getBasename"blog/my-post.html"
print(basename) -- "my-post"

getCompleteOutputPath()

pathInCwd = getCompleteOutputPath( path )

Get the final (possibly rewritten) path for any file path. Example:

local path = "/images/dog.png"
local pathInCwd = getCompleteOutputPath(path)
print(pathInCwd) -- "output/images/dog.png"

Note: The returned path is relative to current working directory, which is always the site root folder. The LuaWebGen API generally only handle paths relative to the content folder - the return value from getCompleteOutputPath() is an exception.

getExtension()

extension = getExtension( path )

Get the extension part of a path or filename.

getFilename()

filename = getFilename( path )

Get the filename part of a path.

getKeys()

keys = getKeys( table )

Get the keys from a table.

img()

html = img( url [, alt="", title ] )
html = img( url [, alt="", useAltAsTitle=false ] )

Create a simple HTML <img> element.

indexOf()

index = indexOf( array, value )

Get the index of a value in an array. Returns nil if the value was not found.

ipairsr()

for index, value in ipairsr( array ) do

Iterate backwards through an array.

isAny()

bool = isAny( valueToCompare, value1, value2, ... )
bool = isAny( valueToCompare, arrayOfValues )

Compare a value against a set of values.

markdown()

html = markdown( markdownText )

Convert markdown to HTML.

max()

n = max( n1, n2, ... )

Alias for math.max().

min()

n = min( n1, n2, ... )

Alias for math.min().

newStringBuilder()

stringBuilder = newStringBuilder( )

Create a handy string builder object, like so:

local b = newStringBuilder()

-- Add things.
b('<img src="icon.png">') -- One argument adds a plain value.
b(42) -- The one argument can be any value.
b('<h1>%s</h1>', entities(page.title)) -- Multiple arguments act like string.format() .

-- Get the contents.
local html = b() -- No arguments returns the concatenated string.

now()

datetime = now( )

Get the current date and time as a datetime string.

pairsSorted()

for key, value in pairsSorted( table ) do

Like pairs(), iterate over the fields of a table, but in alphabetic order of the keys. Note that the function does not detect additions or removals of table fields during the iteration.

prettyUrl()

text = prettyUrl( url )

Make a URL look nice for displaying as text. Example:

local url   = "https://www.animals.com/dogs/"
local label = prettyUrl(url) -- "animals.com/dogs"

echof("<a href="%s">%s</a>", url, label)

Also see a().

printf()

printf( format, ... )

Short form for print(F(format, ...)).

printfOnce()

printfOnce( format, ... )

Print a formatted message only once. Meant for preventing too much spam in the console/log.

printOnce()

printOnce( ... )

Print value(s) only once. Meant for preventing too much spam in the console/log.

removeItem()

removeItem( array, value1, ... )

Remove one or more values from an array. Does not remove duplicate values.

round()

number = round( number )

Round a number.

sortNatural()

array = sortNatural( array [, attribute ] )

Naturally sort an array of strings. If the array contains tables you can sort by a specific attribute instead.

split()

parts = split( string, separatorPattern [, startIndex=1, plain=false ] )

Split a string by a pattern. Example:

local dogs = split("Fido,Grumpy,The Destroyer", ",")

thumb()

html = thumb( imagePath, thumbWidth [, thumbHeight ] [, isLink=false ] )

Create a thumbnail from an image. At least one of thumbWidth or thumbHeight must be a positive number. Example:

{{thumb("/images/gorillaz-fan-art.png", 400, 400, true) -- Max size is 400x400. }}
{{thumb("/images/a-big-tree.gif", 512, true)            -- Max width is 512.    }}
{{thumb("/images/1000-clown-cars.jpg", 0, 350, false)   -- Max height is 350.   }}

toDatetime()

datetime = toDatetime( time )

Convert a time number to a datetime string.

toLua()

luaString = toLua( value )

Convert any value to Lua code. Useful e.g. when sending tables to layouts. Example:

local credits = {
	{what="Fabric", who="Soft Inc."},
	{what="Paint",  who="Bob Bobson Co."},
}

local template = formatTemplate(
	[[
		{{
		page.title = :title:
		P.creditsInPageFooter = :credits:
		}}

		Experience the best carpets around!
	]],
	{
		title   = toLua("Carpets"),
		credits = toLua(credits),
	}
)

generateFromTemplate("products/carpets.md", template)

toTime()

time = toTime( datetime )

Convert a datetime to a normal time number value that standard libraries understand. Example:

local time = toTime(page.publishDate)
local publishYear = os.date("%Y", time)

trim()

string = trim( string )

Remove surrounding whitespace from a string.

trimNewlines()

string = trimNewlines( string )

Remove surrounding newlines from a string.

url()

encodedString = url( urlString )

Percent-encode a URL (spaces become %20 etc.).

Note: url() does not encode HTML entities, like ampersand, thus does not produce valid HTML:

local src = url"/thumb.php?size=200&name=Hello world!"
local html = F('<img src="%s">', src) -- Incorrect.
local html = F('<img src="%s">', entities(src)) -- Correct.

urlAbs()

encodedString = urlAbs( urlString )

Same as url() but also prepends site.baseUrl to relative URLs, making them absolute.

urlExists()

urlExists( url )

Check that a file for the URL exists. Useful e.g. as a sanity check after moving a bunch of pages (that now should have aliases). See validateUrls() for multiple URL checks. Example:

function config.validate()
	local url = "/old-folder/my-post/"
	if not urlExists(url) then
		error("Page is missing: "..url)
	end
end

urlize()

urlPart = urlize( string )

Make a string look like a URL. Useful e.g. when converting page titles to URL slugs.

urlize("Hello, big world!") -- "hello-big-world"

validateUrls()

validateUrls( urls )

Check that files for multiple URLs exist, and trigger an error if any don't exist. Useful e.g. as a sanity check after moving a bunch of pages (that now should have aliases). See urlExists() for single URL checks. Example:

function config.validate()
	validateUrls{
		"/old-folder/my-post/",
		"/work-in-progress/dog.png",
	}
end

warning()

warning( message )

Prints a big warning message to the console. Nothing else happens.

warningOnce()

warningOnce( message )

Prints a big warning message to the console once only. Nothing else happens.

Context-Specific Functions

There are currently 3 contexts where code can run:

  • Templates (HTML, markdown and CSS files)
  • Config (config.before() and config.after())
  • Validation (config.validate())

echo()

echo( string )

Output a string from a template. HTML entities are encoded automatically. Available in templates. Also, see echoRaw().

Note: This function is used under the hood and it's often not necessary to call it manually. For example, these rows do the same thing:

{{date"%Y"}}
{{echo(date"%Y")}}

echof()

echof( format, ... )

Short form for echo(F(format, ...)).

echofRaw()

echofRaw( format, ... )

Short form for echoRaw(F(format, ...)).

echoRaw()

echoRaw( string )

Like echo(), output a string from a template, except HTML entities don't become encoded in this string. Available in templates.

echo   ("a < b") -- Output is "a &lt; b"
echoRaw("a < b") -- Output is "a < b"

Note: In templates, if echo isn't used then HTML entities are sometimes encoded and sometimes not - LuaWebGen tries to be smart about it:

{{"<br>"}}            -- Output is "<br>"
{{"Foo <br>"}}        -- Output is "Foo &lt;br&gt;"

{{echo"<br>"}}        -- Output is "&lt;br&gt;"
{{echo"Foo <br>"}}    -- Output is "Foo &lt;br&gt;"

{{echoRaw"<br>"}}     -- Output is "<br>"
{{echoRaw"Foo <br>"}} -- Output is "Foo <br>"

generateFromTemplate()

page = generateFromTemplate( path, templateString )

Generate a page from a template. Available in config.before() and config.after(). Example:

local path     = "/dogs/fido.md"
local template = "# Fido\n\nFido is fluffy!"
local page     = generateFromTemplate(path, template)
printf("We generated page '%s'.", page.url)

include()

html = include( filename )

Get a HTML template from the layouts folder. Available in templates. Note: Exclude the extension in the filename (e.g. include"footer").

isCurrentUrl()

bool = isCurrentUrl( url )

Check if the relative URL of the current page is url. Example:

{{if isCurrentUrl"/blog/last-post/"}}
You've reached the end!
{{end}}

isCurrentUrlBelow()

bool = isCurrentUrlBelow( urlPrefix )

Check if the relative URL of the current page starts with urlPrefix. Example:

{{local class =  isCurrentUrlBelow"/blog/" and "current" or ""}}

<a href="/blog/" class="{{class}}">Blog</a>

lock()

lock( )

Prevent further changes to page properties, such as page.isDraft and page.publishDate. This allows the current page to be referenced elsewhere even during it's generation. Also see config.autoLockPages. Example:

{{
page.title = "Cute Kittens"
lock()
page.title = "Sly Turtles" -- Error!
}}

outputRaw()

outputRaw( path, contents )

Output any data to a file. Available in config.before() and config.after(). Example:

outputRaw("/docs/versions.txt", "Version 1\nReleased: 2002-10-16\n")

preserveRaw()

preserveRaw( path )

Prevent a previously outputted raw file from being cleaned out after the site generation is done. This function makes it possible to not having to call outputRaw() every time the site builds which could decrease build time. Available in config.before() and config.after().

Note: This functionality is automatically used for all raw files in the content folder.

subpages()

pages = subpages( [ allowCurrentPageToBeIncluded=false ] )

Recursively get all pages in the current folder and below, sorted by page.publishDate. Intended for index pages, but can be used anywhere. Available in templates. Example:

# Blog Archive

{{fori page in subpages()}}
- [{{page.publishDate}} {{page.title}}]({{page.permalink}})
{{end}}

Note: Two pages in the same folder cannot normally request all subpages - that would result in an infinite loop as LuaWebGen tries to generate all subpages before returning a list of them. However, you can solve this by calling lock() in all relevant pages, or enable config.autoLockPages. This will prevent further changes to essential page information (such as page.isDraft or page.publishDate) and thus allowing the page to be referenced elsewhere even during it's generation.

Another possible solution is to generate at least one of those two pages in config.after().

Clone this wiki locally