-
Notifications
You must be signed in to change notification settings - Fork 3
Functions
a()chooseExistingFile()chooseExistingImage()cssPrefix()date()entities()errorf()F()fileExists()files()find()findAll()formatTemplate()generatorMeta()getBasename()getExtension()getFilename()getKeys()img()indexOf()isAny()markdown()max()min()newBuffer()printf()printfOnce()printOnce()removeItem()round()sortNatural()split()thumb()toLua()toTime()trim()trimNewlines()url()urlAbs()urlExists()urlize()validateUrls()warning()warningOnce()
html = a( url [, label=prettyUrl ] )
Create a simple HTML <a> element.
path = chooseExistingFile( pathWithoutExtension, extensions )
Return the path of an existing file with any of the specified extensions. Returns nil if no file exists.
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).
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;"string = date( format [, time=now ] )
Alias for os.date().
(See the C docs for date format.)
html = entities( text )
Encode HTML entities, e.g. < to <.
errorf( [ level=1, ] format, ... )
Trigger an error with a formatted message.
Short form for error(F(format, ...), level).
string = F( format, ... )
Alias for string.format().
bool = fileExists( path )
Check if a file exists in the content folder.
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)item, index = find( array, attribute, value )
Get the item in the array whose attribute is value. Returns nil if no item is found.
items = findAll( array, attribute, value )
Get all items in the array whose attribute is value.
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, the title is in the Lua code.
thing = "bones",
}
)
generateFromTemplate("dogs/info.md", template)Also see toLua().
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.
basename = getBasename( filename )
Remove the extension from a filename. Example:
local basename = getBasename"blog/my-post.html"
print(basename) -- "my-post"extension = getExtension( path )
Get the extension part of a path or filename.
filename = getFilename( path )
Get the filename part of a path.
keys = getKeys( table )
Get the keys from a table.
html = img( url [, alt="", title ] )
html = img( url [, alt="", useAltAsTitle=false ] )
Create a simple HTML <img> element.
index = indexOf( array, value )
Get the index of a value in an array. Returns nil if the value was not found.
bool = isAny( valueToCompare, value1, value2, ... )
bool = isAny( valueToCompare, arrayOfValues )
Compare a value against a set of values.
html = markdown( markdownText )
Convert markdown to HTML.
n = max( n1, n2, ... )
Alias for math.max().
n = min( n1, n2, ... )
Alias for math.min().
buffer = newBuffer( )
Create a handy string buffer object, like so:
local b = newBuffer()
-- Add things.
b('<img src="icon.png">') -- One argument adds a plain string.
b('<h1>%s</h1>', entities(page.title)) -- Multiple arguments acts like string.format() .
-- Get the contents.
local html = b() -- No arguments returns the buffer as a string.printf( format, ... )
Short form for print(F(format, ...)).
printfOnce( format, ... )
Print a formatted message only once. Meant for preventing too much spam in the console/log.
printOnce( ... )
Print value(s) only once. Meant for preventing too much spam in the console/log.
removeItem( array, value1, ... )
Remove one or more values from an array. Does not remove duplicate values.
number = round( number )
Round a number.
array = sortNatural( array [, attribute ] )
Naturally sort an array of strings. If the array contains tables you can sort by a specific attribute instead.
parts = split( string, separatorPattern [, startIndex=1, plain=false ] )
Split a string by a pattern. Example:
local dogs = split("Fido,Grumpy,The Destroyer", ",")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)}}
{{thumb("/images/a-big-tree.gif", 512, true)}}
{{thumb("/images/1000-clown-cars.jpg", 0, 350, false)}}
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)time = toTime( datetime )
Convert a datetime used in LuaWebGen to a normal time value that standard libraries understand.
datetime must have the format "YYYY-MM-DD hh:mm:ss".
Example:
local time = toTime(page.publishDate)
local publishYear = os.date("%Y", time)string = trim( string )
Remove surrounding whitespace from a string.
string = trimNewlines( string )
Remove surrounding newlines from a string.
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.
encodedString = urlAbs( urlString )
Same as url() but also prepends site.baseUrl to relative URLs, making them absolute.
urlExists( url )
Check that files for URLs exist. Useful e.g. after moving a bunch of pages (that now should have aliases). Example:
function config.validate()
local url = "/old-folder/my-post/"
if not urlExists(url) then
error("Page is missing: "..url)
end
endurlPart = 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( url )
Check that files for URLs exist. Useful e.g. after moving a bunch of pages (that now should have aliases). Example:
function config.validate()
validateUrls{
"/old-folder/my-post/",
"/work-in-progress/dog.png",
}
endwarning( message )
Prints a big warning message to the console. Nothing else happens.
warningOnce( message )
Prints a big warning message to the console once only. Nothing else happens.
echo()echoRaw()generateFromTemplate()include()isCurrentUrl()isCurrentUrlBelow()outputRaw()subpages()
There are currently 3 contexts where code can run:
- Templates (HTML, markdown and CSS files)
- Config (
config.before()andconfig.after()) - Validation (
config.validate())
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")}}
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 < 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 <br>" {{echo"<br>"}} -- Output is "<br>" {{echo"Foo <br>"}} -- Output is "Foo <br>" {{echoRaw"<br>"}} -- Output is "<br>" {{echoRaw"Foo <br>"}} -- Output is "Foo <br>"
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)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").
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}}
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>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")pages = subpages( )
Recursively get all pages in the current folder and below, sorted by publishDate. Intended for index pages. 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 request all subpages - that would result in an infinite loop as LuaWebGen tries to generate all subpages before returning a list of them. You'll have to generate at least one of those two pages in
config.after().
- Home
- Command Line
- Site Configuration
- Embedding Lua
- Constants
- Functions
- Objects
- Other Modules and Information