Bolt Cheatsheet

You are reading the official Bolt Cheat sheet. This page contains a wealth of information, packed together in a small package.

Use CTRL-F or OPTION-F to quickly search inside the cheat sheet.

1. Sample theme structure

This is the common structure of a Bolt theme. The files are located in themes/. Define the theme to be used with the theme: setting in the global config.yml.

Filename Function

index.twig

Homepage or root of the site, i.e. /

listing.twig

listing page for overview of pages, entries or listings per category or search results, e.g. /entries, /tags/movies, /search?search=lorem

entry.twig

single page for a record of the 'entries' ContentType, e.g. /entry/lorum-ipsum

record.twig

fallback single template for any ContentType that doesn't have its own single record template, e.g. /showcase/dolor-sit

_aside.twig

template for the sidebar

_footer.twig

template for the common footer of all pages

_header.twig

template for the common header of all pages

_recordfooter.twig

meta-information for a single page or record

_sub_menu.twig

template for the markup of the menu. See also menu.yml for the contents

_sub_searchbox.twig

template for the markup for the search box.

images/

graphical assets used in the theme

javascripts/

any used javascripts should go in here

css/

contains the (compiled) CSS for the theme

scss/

optional folder for Sass source files, to be compiled into CSS.

config.yml

optional config file with settings specific to the theme.

Read more: Templates and routing

2. Template cascading

Bolt has some rules to help you quickly build custom templates for your site. If your template is named exactly like the singular_slug or slug for the content type or record it will automatically be used.

Rules for Records

The ContentType has a ‘templateselect field’ and a template is selected for this record.

The ContentType definition has a value for record_template.

Bolt will check if a template with a suited name exists, like entry.twig or page.twig

record_template is set in the global config.yml

If no other rule matches, Bolt will use a template named record.twig

Read more: Automatic template selection

You can define one or more menus in the file app/config/menu.yml, which can then be inserted in your templates using the {{ menu() }} tag.

Example

main:
  - label: Home
      title: This is the first menu item. Fo shizzle!
      path: homepage
      class: first
  - label: Second item
      path: entry/1

Insert the menu in the site, using the {{ menu() }} tag. Add a menu_main.twig file in your theme folder, replacing 'name' with the name of your menu.

Example

<ul>{% for item in menu %}
  <li>
    <a href='{{ item.link }}'>{{item.label}}</a>
  </li>
{% endfor %}</ul>

Read more: Menus in the docs

4. ContentTypes and contenttypes.yml

The ContentTypes in Bolt are defined in the file app/config/contenttypes.yml. You can edit this file directly, or from within the Bolt interface under 'Settings' > 'ContentTypes'.

Key Function

name

The name of the ContentType, should be plural.

singular_name

The name of one record in the ContentType. Should be singular.

slug

(optional) This determines the slug of the ContentType, and therefore the URLs that are generated for this ContentType.

singular_slug

(optional) This determines the slug of the a single record in this ContentType, and therefore the URLs that are generated.

description

(optional) A short description of the ContentType.

fields

The fields that make up the content in this ContentType. See the section Field definitions for details.

taxonomy

An array listing the different taxonomies used by this ContentType. See the section on Taxonomies for details.

relations

An array listing the different relations available to this ContentType. See the section on Relations for details.

record_template

The default template to use, when displaying a single record of this ContentType.

listing_template

The default template to use, when displaying an overview of records of this ContentType.

listing_records

The amount of records to show on a single overview page in the frontend.

sort

(optional) The default sorting of this ContentType. For example -datecreated.

recordsperpage

(optional) The amount of records shown on each page in the Bolt backend. If there are more records, they will be paginated.

show_on_dashboard

(optional) When set to false the ContentType will not appear in the 'Recently edited …' list on the Dashboard page.

show_in_menu

(optional) When set to false the ContentType will show in a submenu instead of as a top level menu. Can also be set to a word or sentence to group ContentTypes.

default_status

(optional) The default status for new records in this ContentType, i.e. published, held, draft or timed.

searchable

(optional) A boolean value to determine whether this ContentType should show up in search results.

viewless

(optional) A boolean value to determine whether this ContentType should have routing or not.

icon_many

(optional) A Font Awesome icon to be used in the sidebar for this ContentType. For example: fa:cubes

icon_one

(optional) A Font Awesome icon to be used in the sidebar for a single record of this ContentType. For example: fa:cube.

Read more: Defining ContentTypes in the docs

5. Fields for ContentTypes in contenttypes.yml

The fields option in a ContentType lists the fields for that ContentType. The available fields are below. See also Field options

Key function

text

Simple text-input, for single-line fields

slug

The slug is a required field, but you can include it in the fields list to customize it.

image

Simple image upload/select field.

imagelist

A field to create a list of images. Useful for slideshows and galleries.

file

Simple file upload/select field. Also set extensions and the global setting for accept_file_types in the main config.yml.

filelist

A more complex upload/select field.

html

WYSIWYG HTML field.

textarea

Simple multi-line textarea input, for longer texts without HTML markup.

select

A drop-down list to make a pre-defined selection from.

video

A set of fields for embedding videos from websites like Youtube and Vimeo.

embed

A generic embed field for different sources like YouTube, Vimeo, Twitter, SoundCloud and those compatible with the OEmbed standard.

geolocation

A set of fields for easy selection of a geolocation (latitude/longitude). Requires google_api_key to be set in config.yml.

date

Datepicker widget, to set/select a date.

datetime

Similar to the date field, but adds an additional field for time.

integer

A field to store integers.

float

A field to store (floating point) numbers.

Read more: Field definitions in the docs

6. Field options for ContentTypes in contenttypes.yml

Each field in the ContentType is an array with several options. The available options are below. See also Field definitions

Key function

class: large

Will show the field in a larger font, for text fields.

class: wide

Will show the field extra wide, for filling out the column. text fields only.

class: narrow

Will show the field narrow, for fields that should take only a couple of characters. For text fields only.

variant: inline

Will show the field to the right of the label, taking up less space vertically. For text fields only.

label: Foo

If omitted, the name of the field will be used as a label in the edit-screen. Replace 'Foo' with the desired label of the field.

height: 150px

For html and textarea fields, this will determine the height in the edit-screen.

index: true

Add a database index for this field, use with caution.

group: Foo

Separate this and all subsequent fields (until another group declaration) into a tab with the name 'Foo'. Replace 'Foo' with the desired label of the tab.

prefix: ..

HTML to add before the field.

postfix: ..

HTML to add after the field.

separator: true

Add <hr> divider after the field.

default: ..

The default value for a field, if applicable. See below for an example.

required: true

Use this to make a field required. Only works on text, textarea, html, date, datetime, float and integer fields.

readonly: true

Use this to make a field read-only. Only works on float, integer and text fields.

pattern: ..

Use this to validate a field against a certain pattern, using regular expressions.

allowtwig: true

Explicitly allow twig to be used in this field.

info: ..

Use for displaying extra information about the field.

extensions: [ .. ]

A list of allowed file extensions for uploading. Used with file, filelist, image and imagelist

upload: foo

A custom path for uploaded files. Used with file, filelist, image and imagelist

Read more: Field definitions in the docs

7. Relationships

You can use relationships between records by adding a relation to a ContentType. Relationships are always bidirectional.

Example

relations:
    pages:
        multiple: false
        label: Select a page
        order: -id

Accessing record.relation will give you nothing but the ContentTypes and id’s: {{ print(record.relation) }}. To get the actual related records, use {% set relatedrecords = record.related() %}.

Read more: Relationships in the docs

8. Taxonomies and taxonomy.yml

You can create taxonomies by adding them to taxonomy.yml. You can define your own taxonomies, and choose how they behave.

Type Function

tags

Tags are a sort of ‘freeform’ labeling. Each record can have several tags, that do not have to be selected from a predefined list.

categories

Categories are chosen pre-defined categorizations for your record. These are often found on weblogs.

grouping

Grouping is like categories but it is - by definition - more strict. When a grouping applies to a certain record, that record should be viewed as a part of the other records with the same grouping.

Read more: Taxonomies in the docs

9. Permissions and permissions.yml

The permissions needed to perform an action are configurable by editing app/config/permissions.yml. This can be done either directly, or through Bolt’s back-end UI. By changing the permissions you basically change the way how people can interact with Bolt, and who is allowed to do what.

Read more: Permissions in the docs

10. Routing and routing.yml

Bolt allows you to configure the routing to your needs. This basically means that you can configure Bolt to generate and interpret URLs the way you need them to be. There are some caveats with regards to correct canonical URLs, but otherwise you can change it to anything you like. The easiest way to add your own is to follow the examples defined in the distributed routing.yml.dist file. The order of the routes is important because it is routing is done on a first-come first-serve basis.

Read more: Routing in the docs


11. Twig

The templates in Bolt are written in Twig. This is a fast, flexible and elegant templating language.

Syntax Meaning

{{ … }}

Output someting, like 'echo' or 'print'.

{% … %}

Do someting, like 'for', 'if' or 'setcontent'.

{# … #}

Do nothing, this is a comment.

foo

A variable named 'foo'.

5, 3.1415

Integers and floating point numbers can be used as-is.

'foo'

A literal sting, that has the value 'foo'.

['foo', 'bar', 5]

An array containing three elements.

{'a': 'foo', 'b': 5}

A hash is a list of keys and value-pairs, separated by a comma.

12. Setting variables

Syntax Meaning

{% set foo = 'bar' %}

Set the variable foo to contain the string bar.

{% set foo = [1, 2, 3] %}

You can set variables to contain literals, arrays, hashes, etc.

{% set foo = 'Hello ' ~ name %}
{% set foo = foo|merge(bar) %}

Use set to append strings or merge arrays.

13. Including other templates

Use this to include another Twig template in the current template. Twig parses the template like any other template, so you can use any tags in your included template that you would use in the ‘main’ template. You can also use include inside the included templates."

Syntax Meaning

{% include '_header.twig' %}

Includes the file _header.twig.

{% set v = {'title': 'Hello!'} %}
{% include '_header.twig' with v %}

You can set variables to contain literals, arrays, hashes, etc.

An alternative to using 'include', is to set up your templates using Template Inheritance. This is a method of defining a base template, and then expand it in more detail in the templates that extend this base template. See the section on Template inheritance on the twig website.

Read more: Including other templates, Template inheritance

14. Using macros in Twig

Macros in Twig can be thought of as functions in PHP or Javascript.

Syntax Explanation

{% macro foo(var) %}
    Foo and {{ var }}
{% endmacro %}

Define a macro in '_macros.twig'

{% import '_macros.twig' as m %}

Import the macros in your template.

{{ m.foo('bar') }}

Call the macro in your template.

If you've defined the macros in the same file, you need to import them, using _self: {% import _self as macro %}

Read more: Macro in the Twig docs

15. The {% if %} control structure

The if tag is used to check if 'something' (an expression) is true or false, and act accordingly.

Syntax Explanation

{% if record.title %}
    {{ record.title }}
{% else %}
    No title given.
{% endif %}

Simple 'if' statement.

{% if user.name == 'bob' %}
    Oh, it's you…
{% else %}
    Well, hello {{ user.name }}
{% endif %}

'if' statement, with an else clause.

Read more: If in the Twig docs

16. The {% for %} control structure

The for tag is used to iterate over a hash or array, repeating the same code for each element.

Syntax Explanation

{% for u in users %}
    <a href='{{ u.email }}'>
    {{ u.name }}</a>
{% else %}
    No active users.
{% endfor %}

Simple 'for' loop. Note the use of else if there are no items.

{% for u in users if u.active %}

You can use 'if' in the 'for' statement.

{% for u in users|sort('name') %}

Use a filter, for example to sort on u.name.

Read more: For in the Twig docs

17. Bolt functions in Twig

Functions in twig look like this: {{ foo('bar', 1, 2) }}. A function can take zero or more parameters. Basically, a function does something, and then returns the result for output or further processing.

Name Function

dump(var)

Print a nicely formatted dump of the contents of var.

backtrace()

Print a formatted dump of the backtrace stack, with the "followed path" through the code.

excerpt(var, length)

Create a short excerpt from var, without HTML formatting, restricted by length characters. var can be a 'record' object, a single value from a 'record' or a regular string.*

markdown()

Parse a given string as Markdown. *

current()

Checks if a given record corresponds to the page being shown in the browser. *

htmllang

Returns the language value for in tags where the language attribute is required

pager

Output a simple pager, for paginated listing pages.

debugbar

Switch the debugbar on or off.

ismobileclient

Check if the current page is viewed on a mobile device

menu

Output a menu. See the section on menus.

isallowed($what, $content)

Check if a certain action is allowed for the current user (and possibly content item)

thumbnail(filename, w, h)

Helper function to make a path to an image thumbnail. *

showimage(filename, w, h)

Helper function to show an image on a rendered page. *

image(filename, w, h)

Helper function to make a path to an image. *

popup(filename, w, h)

Helper function to wrap an image in a Magnific popup HTML tag, with thumbnail. *

imageinfo(filename)

Get an array with the dimensions of an image, together with its aspectratio and some other info. *

file_exists(filename)

Check if a file exists

fields(record)

Ouputs all or some fields from a record. Many options are available and documented here

request(para, from)

Return the requested parameter from $_REQUEST, $_GET or $_POST.

first / last()

Returns the first item of an array. *

shuffle(array)

Randomly shuffle the contents of a passed array. *

__(label)

Translate a label to the current localisation settings. *

redirect(path)

Redirect the browser to another page.

Note: functions() marked with an '*' can be used as |filter as well.

18. Default functions in Twig

Bolt uses the Twig template engine. As such, all default twig {{ functions() }} also work in Bolt. Most of these have a similar meaning in plain PHP or Javascript. The available functions are: attribute, block, constant, cycle, date, dump, include, max, min, parent, random, range, source, template_from_string.

19. The {% setcontent %} tag

The {% setcontent %} tag is one of the most important tags in Bolt, because it allows you to get content in any location to use however you need.

Parameter Function

variable name

The first parameter (before the '=') is always the variable that will contain the result set

'contenttype'

The name of the ContentType to fetch records from

'contenttype/latest/10'

get the latest 10 records from contenttype

'contenttype/slug'

get the record from contenttype with the slug slug

'contenttype/123'

get the record from contenttype with the id 123

where { username: 'bob' }

use where to define what needs to be fetched.

where { title: '%ipsum%' }

use % in your where statement to use 'LIKE' matching.

where { tags: 'book || movie' }

you can also use taxonomies in your where.

where { datepublish: '<today' }

use shortcuts like 'now', 'today', 'tomorrow' for date selection.

Read more: {% setcontent %} in the documentation

20. Twig default tags

Bolt uses the Twig template engine. As such, all default twig {% tags %} also work in Bolt. The available tags are: autoescape, block, do, embed, extends, filter, flush, for, from, if, import, include, macro, sandbox, set, spaceless, use, verbatim.

21. Bolt Filters in Twig

Filters in twig look like this: {{ 'foo'|filter }}, and can take optional parameters. A filter basically transforms whatever you put into it, so it can be processed further. Filters can be chained together, for example: {{ record.title|excerpt(20)|lower }}.

Name Function

localedatetime(date)

Returns the date and time in a particular format. Takes the locale into account. See strftime() for fomatting options

twig(string)

Formats the given string as Twig in HTML

ucfirst(string)

Make a string's first character uppercase.

slug(string)

Return the 'sluggified' version of a string: 'Lørüm Ipsum' -> 'lorum-ipsum'

shy(string)

Add 'soft hyphens' to a string. These normally inivisble hyphens, allow a browser to wrap a string, if it wouldn't fit the layout otherwise.

safestring(string)

Return a 'safe string' version of a given string: 'Lørüm Ipsum' -> 'lorum ipsum'

order(array, key)

Order an array, based on the given 'key'.

json_decode

Leniently decode a serialized compound data structure to an array / object. Note: json_encode does the opposite, and is built-in in Twig.

22. Default filters in Twig

Bolt uses the Twig template engine. As such, all default twig {{ |filters }} also work in Bolt. Most of these have a similar meaning in plain PHP or Javascript. The available filters are: abs, batch, capitalize, convert_encoding, date, date_modify, default, escape, first, format, join, json_encode, keys, last, length, lower, merge, nl2br, number_format, raw, replace, reverse, round, slice, sort, split, striptags, title, trim, upper, url_encode.

23. Twig tests in Bolt

Name Function

testjson

Test whether a passed string contains valid JSON

24. Default tests in Twig

Bolt uses the Twig template engine. As such, all default twig tests also work in Bolt. Most of these have a similar meaning in plain PHP or Javascript. The available tests are: constant, defined, divisibleby, empty, even, iterable, null, odd, sameas.


25. Default variables in Twig

Key Value

user

An array containing the specifics of the currently logged on user. Empty if the user is not logged on.

bolt_name

A string containing the current name of the Bolt version.

bolt_version

The current version number, like '2.0.2'.

frontend

A boolean that's true, if we're currently rendering a template in the frontend.

backend

A boolean that's true, if we're currently rendering a template in the backend.

async

A boolean that's true, if we're currently rendering a template that's called asynchronously.

users

An array containing the users in the system.

theme

An array, containing the theme-specific settings, as defined in the config.yml file in the theme folder.

config

An object containing the current configuration. See the block Config object.

26. Debugging Bolt

If you’re coding and you want to get a quick look at whatever variable or object you’re trying to manipulate, you can dump its contents to the browser. In templates, use the following: The variable can be a normal variable, a single record, multiple records, or other stuff.

Code Function

{{ dump(variable) }}

Dump 'variable' in the template.

dump($variable);

Dump 'variable' in your code.

{{ backtrace() }}

Get a backtrace throught the code to the current point in the execution, in the template.

dump(debug_backtrace());

Get a backtrace throught the code to the current point in the execution, in your code. The optional parameter denotes the maximum depth of the output of the backtrace.

Read more: {{ dump() }} in the documentation

27. The app.request variable.

The app.request variable holds all request variables, like those in $_GET and $_POST, but also session variables and attributes set by Bolt itself. Use {{ app.request.get('foo') }} to access them.

Key Value

_controller

An array with the specifics of the current controller

_route

The name of the (current) matching route.

_route_params

Parameters of the currently matching route, if there are any.

app

The current app object. Usually Bolt\Application, unless you're doing something really weird.