Marko
================
[](https://travis-ci.org/marko-js/marko) [](https://gitter.im/marko-js/marko?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[](https://nodei.co/npm/marko/)

Marko is an eBay open source HTML-based templating engine that is a perfect match for Node.js and any web browser. Marko is [extremely fast](https://github.com/marko-js/templating-benchmarks) while also supporting streaming and asynchronous rendering. Marko also supports custom tags and custom attributes to make it easy for developers to extend the HTML grammar with new building blocks. Marko compiles templates into _readable_ Node.js JavaScript modules that use `require()` to import all dependencies, thus making it effortless to bundle up compiled templates for use in the browser using your favorite JavaScript module bundler. Marko avoids the ugliness associated with many other templating engines by completely avoiding global variables and global helpers.
Marko was founded on the philosophy that an HTML-based templating language is more natural and intuitive for generating HTML. Because the Marko compiler understands the structure of the HTML document, the directives in template files are less obtrusive and more powerful. Marko also retains the full power of JavaScript by allowing JavaScript expressions inside templates.
```xml
Hello ${data.name}!
$color
No colors!
```
Marko is a perfect match for Node.js since it supports writing directly to an output stream so that HTML can be sent over the wire sooner. Marko automatically flushes around asynchronous fragments so that the HTML is delivered in the optimized number of chunks. Because Marko is an asynchronous templating language, additional data can be asynchronously fetched even after rendering has begun. These characteristics make Marko an excellent choice for creating high performance websites.
```javascript
require("./template.marko").render({
message: "It doesn't get any easier than this!"
},
process.stdout)
```
For building rich UI components with client-side behavior please check out the companion [marko-widgets](https://github.com/marko-js/marko-widgets) taglib.
__[Try Marko Online!](http://raptorjs.org/marko/try-online/)__

Improved syntax highlighting available for [Atom](https://atom.io/) by installing the [language-marko](https://atom.io/packages/language-marko) package and for [Sublime Text](http://www.sublimetext.com/) by installing the [marko-sublime](https://github.com/merwan7/sublime-marko) package.
# Sample Code
A basic template with text replacement, looping and conditionals is shown below:
```xml
Hello ${data.name}!
$color
No colors!
```
The template can then be rendered as shown in the following sample code:
```javascript
require('marko/node-require').install();
var template = require('./hello.marko');
template.render({
name: 'World',
colors: ["red", "green", "blue"]
},
function(err, output) {
console.log(output);
});
```
The output of running the above program will be the following (formatted for readability):
```xml
Hello World!
red
green
blue
```
For comparison, given the following data consisting of an empty array of colors:
```javascript
{
name: 'World',
colors: []
}
```
The output would be the following:
```xml
Hello World!
No colors!
```
The streaming API can be used to stream the output to an HTTP response stream or any other writable stream. For example, with Express:
```javascript
var template = require('./template.marko');
app.get('/profile', function(req, res) {
template.stream({
name: 'Frank'
})
.pipe(res);
});
```
Marko also supports custom tags so you can easily extend the HTML grammar to support things like the following:
```xml
Welcome to Marko!
Content for Home
Content for Profile
Content for Messages
```
The above template is a very simple way to generate the much more complicated HTML output shown below:
```xml
```
The custom tags encapsulate rendering logic and help avoid repeating the same HTML (and potentially the same mistakes).
# Table of Contents
- [Installation](#installation)
- [Another Templating Language?](#another-templating-language)
- [Design Philosophy](#design-philosophy)
- [Usage](#usage)
- [Template Loading](#template-loading)
- [Template Rendering](#template-rendering)
- [Callback API](#callback-api)
- [Streaming API](#streaming-api)
- [Synchronous API](#synchronous-api)
- [Asynchronous Rendering API](#asynchronous-rendering-api)
- [Browser-side Rendering](#browser-side-rendering)
- [Using Lasso.js](#using-lassojs)
- [Using Browserify](#using-browserify)
- [Template Compilation](#template-compilation)
- [Sample Compiled Template](#sample-compiled-template)
- [Hot reloading templates](#hot-reloading-templates)
- [Language Guide](#language-guide)
- [Template Directives Overview](#template-directives-overview)
- [Text Replacement](#text-replacement)
- [Expressions](#expressions)
- [Includes](#includes)
- [Variables](#variables)
- [Conditionals](#conditionals)
- [if...else-if...else](#ifelse-ifelse)
- [Shorthand Conditionals](#shorthand-conditionals)
- [Conditional Attributes](#conditional-attributes)
- [Looping](#looping)
- [for](#for)
- [Loop Status Variable](#loop-status-variable)
- [Loop Separator](#loop-separator)
- [Range Looping](#range-looping)
- [Property Looping](#property-looping)
- [Custom Iterator](#custom-iterator)
- [Macros](#macros)
- [def](#def)
- [invoke](#invoke)
- [Structure Manipulation](#structure-manipulation)
- [attrs](#attrs)
- [body-only-if](#body-only-if)
- [Comments](#comments)
- [Whitespace](#whitespace)
- [Helpers](#helpers)
- [Global Properties](#global-properties)
- [Custom Tags and Attributes](#custom-tags-and-attributes)
- [Async Taglib](#async-taglib)
- [Layout Taglib](#layout-taglib)
- [API](#api)
- [require('marko')](#requiremarko)
- [Methods](#methods)
- [load(templatePath[, options]) : Template](#loadtemplatepath-options--template)
- [createWriter([stream]) : AsyncWriter](#createwriterstream--asyncwriter)
- [render(templatePath, templateData, stream.Writable)](#rendertemplatepath-templatedata-streamwritable)
- [render(templatePath, templateData, callback)](#rendertemplatepath-templatedata-callback)
- [stream(templatePath, templateData) : stream.Readable](#streamtemplatepath-templatedata--streamreadable)
- [Properties](#properties)
- [helpers](#helpers)
- [Template](#template)
- [Template](#template-1)
- [Methods](#methods-1)
- [renderSync(templateData) : String](#rendersynctemplatedata--string)
- [render(templateData, stream.Writable)](#rendertemplatedata-streamwritable)
- [render(templateData, AsyncWriter)](#rendertemplatedata-asyncwriter)
- [render(templateData, callback)](#rendertemplatedata-callback)
- [stream(templateData) : stream.Readable](#streamtemplatedata--streamreadable)
- [Custom Taglibs](#custom-taglibs)
- [Tag Renderer](#tag-renderer)
- [marko-taglib.json](#marko-taglibjson)
- [Sample Taglib](#sample-taglib)
- [Defining Tags](#defining-tags)
- [Defining Attributes](#defining-attributes)
- [Scanning for Tags](#scanning-for-tags)
- [Nested Tags](#nested-tags)
- [Taglib Discovery](#taglib-discovery)
- [FAQ](#faq)
- [Additional Resources](#additional-resources)
- [Further Reading](#further-reading)
- [Screencasts](#screencasts)
- [Demo Apps](#demo-apps)
- [Tools](#tools)
- [Changelog](#changelog)
- [Discuss](#discuss)
- [Contributors](#contributors)
- [Contribute](#contribute)
- [License](#license)
# Installation
To install the `marko` module into your project you should use the following command:
```bash
npm install marko --save
```
To install the optional `markoc` command line interface to compile templates you can use the following command:
```bash
npm install marko --global
```
# Another Templating Language?
Most front-end developers are familiar with, and comfortable with, templating languages such as [Handlebars](https://github.com/wycats/handlebars.js), [Dust](https://github.com/linkedin/dustjs) or [Mustache](http://mustache.github.io/) so why was Marko introduced?
What makes Marko different is that it is an HTML-based templating language that does not rely on a custom language grammar. Any HTML file is a valid Marko template and vice-versa, and the Marko compiler uses an [off-the-shelf HTML parser](https://github.com/fb55/htmlparser2). Because Marko understands the HTML structure of the templates, it can do more powerful things that would not be possible in a text-based templating languages such as Handlerbars, Dust or Mustache. Marko allows developers to _extend the HTML language_ by introducing custom HTML elements and attributes. On top of that, utilizing the HTML structure for applying templating directives makes templates more readable and allows data templates to more closely resemble the final HTML structure.
Let's compare Marko with Handlebars (a text-based templating language):
__Handlebars:__
```xml
Hello {{name}}!
{{#if colors}}
{{#each colors}}
{{this}}
{{/each}}
{{else}}
No colors!
{{/if}}
```
__Marko:__
```xml
Hello ${data.name}!
${color}
No colors!
```
A few things to note for the Marko template:
* Less lines of code
* Less lines are "touched" to make the template dynamic
* Only opening tags are modified for conditionals and looping
Beyond Marko being an HTML-based templating language, it was also designed with extreme performance and extensibility in mind. The Marko compiler gives developers full control over how templates are compiled to JavaScript and the runtime was designed to be as efficient as possible. Marko fully embraces the JavaScript language for better performance and flexibility (e.g. favoring JavaScript expressions over a custom expression language).
Finally, another distinguishing feature of Marko is that it supports _asynchronous template rendering_. This powerful feature allows portions of the template to be rendered asynchronously. Instead of waiting for all data to come back from remote services before beginning to render the template, you can now immediately start rendering the template and the portions of the template that depend on asynchronous data will render as soon as the asynchronous data becomes available. The Marko rendering engine ensures that the final HTML will be streamed out in the correct order.
# Design Philosophy
* __Readable:__ Templates should be as close to the output HTML as possible to keep templates readable. Cryptic syntax and symbols should be avoided.
* __Simple:__ The number of new concepts should be minimized and complexity should be avoided.
* __Extensible:__ The template engine should be easily extensible at both compile-time and runtime.
* __High Performance:__ Runtime and compiled output should be optimized for low CPU and memory usage and have a small footprint. All expressions should be native JavaScript to avoid runtime interpretation.
* __Not Restrictive:__ Whether or not to go less logic or more logic is up to the developer.
* __Asynchronous and Streaming Output:__ It should be possible to render HTML out-of-order, but the output HTML should be streamed out in the correct order. This minimizes idle time and reduces the time to first byte.
* __Intuitive:__ The templating engine should introduce as few surprises as possible.
* __Browser and Server Compatibility:__ Templates should compile down to JavaScript that can be executed on both the server and the client.
* __Debuggable:__ Compiled JavaScript should be debuggable and readable.
* __Compile-Time Checks:__ Syntax, custom tags and custom attributes should be validated at compile-time.
* __Tools Support:__ Tools should be enabled to offer auto-completion and validation for improved productivity and safety.
* __Modular:__ Runtime and compiled templates should be based on CommonJS modules for improved dependency management. Template dependencies (such as custom tags) should be resolved based on a template's file system path instead of relying on a shared registry.
# Usage
## Template Loading
Marko provides a [custom Node.js require extension](https://github.com/marko-js/marko/blob/master/node-require.js) that allows Marko templates to be `require`'d just like a standard JavaScript module. For example:
```javascript
// The following line installs the Node.js require extension
// for `.marko` files. Once installed, `*.marko` files can be
// required just like any other JavaScript modules.
require('marko/node-require').install();
// ...
// Load a Marko template by requiring a .marko file:
var template = require('./template.marko');
```
_NOTE: The Node.js require extension for Marko templates simply hooks into the Node.js module loading system to automatically compile `.marko` template files to CommonJS JavaScript modules when they are first required and the loaded `Template` instance is exported by the compiled template module. Internally, the implementation for `require('marko/node-require').install()` will use `require.extensions[extension] = function markoExtension(module, filename) { ... }` to register the Node.js require extension._
_NOTE 2: The require extension only needs to be installed once, but it does not hurt if it is installed multiple times. For example, it is okay if the main app registers the require extension and an installed module also registers the require extension. The require extension will always resolve the proper `marko` module relative to the template being required so that there can still be multiple versions of marko in use for a single app._
If you prefer to not rely on the require extension for Marko templates, the following code will work as well:
```javascript
var template = require('marko').load(require.resolve('./template.marko'));
```
A loaded Marko template has multiple methods for rendering the template as described in the next section.
## Template Rendering
### Callback API
```javascript
var template = require('./template.marko');
template.render({
name: 'Frank',
count: 30
},
function(err, output) {
if (err) {
console.error('Rendering failed');
return;
}
console.log('Output HTML: ' + output);
});
```
### Streaming API
```javascript
var template = require('./template.marko');
var out = require('fs').createWriteStream('index.html', {encoding: 'utf8'});
// Render the template to 'index.html'
template.stream({
name: 'Frank',
count: 30
})
.pipe(out);
```
Alternatively, you can render directly to an existing stream to avoid creating an intermediate stream:
```javascript
var template = require('./template.marko');
var out = require('fs').createWriteStream('index.html', {encoding: 'utf8'});
// Render the template to 'index.html'
template.render({
name: 'Frank',
count: 30
}, out);
```
_NOTE:_ This will end the target output stream.
### Synchronous API
If you know that your template rendering requires no asynchronous rendering then you can use the synchronous API to render a template to a String:
```javascript
var template = require('./template.marko');
var output = template.renderSync({
name: 'Frank',
count: 30
});
console.log('Output HTML: ' + output);
```
### Asynchronous Rendering API
```javascript
var fs = require('fs');
var template = require('./template.marko');
var out = marko.createWriter(fs.createWriteStream('index.html', {encoding: 'utf8'}));
// Render the first chunk asynchronously (after 1s delay):
var asyncOut = out.beginAsync();
setTimeout(function() {
asyncOut.write('BEGIN ');
asyncOut.end();
}, 1000);
// Render the template to the original writer:
template.render({
name: 'World'
},
out);
// Write the last chunk synchronously:
out.write(' END');
// End the rendering out
out.end();
```
Despite rendering the first chunk asynchronously, the above program will stream out the output in the correct order to `index.html`:
```xml
BEGIN Hello World! END
```
For more details, please see the documentation for the [async-writer](https://github.com/marko-js/async-writer) module.
## Browser-side Rendering
Given the following module code that will be used to render a template on the client-side:
_run.js_:
```javascript
var template = require('./hello.marko');
templatePath.render({
name: 'John'
},
function(err, output) {
document.body.innerHTML = output;
});
```
You can then bundle up the above program for running in the browser using either [Lasso.js](https://github.com/lasso-js/lasso) (recommended) or [browserify](https://github.com/substack/node-browserify).
### Using Lasso.js
The `lasso` CLI can be used to generate resource bundles that includes all application modules and all referenced Marko template files using a command similar to the following:
```bash
# First install the lasso and the lasso-marko plugin
npm install lasso --global
npm install lasso-marko
lasso --main run.js --name my-page --plugins lasso-marko
```
This will produce a JSON file named `build/my-page.html.json` that contains the HTML markup that should be used to include the required JavaScript and CSS resources that resulted from the page optimization.
Alternatively, you can inject the HTML markup into a static HTML file using the following command:
```bash
lasso --main run.js --name my-page --plugins lasso-marko --inject-into my-page.html
```
### Using Browserify
The `markoify` transform for browserify must be enabled in order to automatically compile and include referenced Marko template files.
```bash
# Install the markoify plugin from npm:
npm install markoify --save
# Build the browser bundle:
browserify -t markoify run.js > browser.js
```
## Template Compilation
The Marko compiler produces a Node.js-compatible, CommonJS module as output. This output format has the advantage that compiled template modules can benefit from a context-aware module loader and templates can easily be transported to work in the browser using [Lasso.js](https://github.com/lasso-js/lasso) or [Browserify](https://github.com/substack/node-browserify).
The `marko` module will automatically compile templates loaded by your application on the server, but you can also choose to precompile all templates. This can be helpful as a build or test step to catch errors early.
You can either use the command line interface or the JavaScript API to compile a Marko template file. To use the CLI you must first install the `marko` module globally using the following command:
```bash
npm install marko --global
```
You can then compile single templates using the following command:
```bash
markoc hello.marko
```
This will produce a file named `hello.marko.js` next to the original file.
You can also recursively compile all templates in the current directory (the `node_modules` and `.*` directories will be ignored by default)
```bash
markoc .
```
You can also specify multiple directories or files
```bash
markoc foo/ bar/ template.marko
```
To delete all of the generated `*.marko.js` files you can add the `--clean` argument. For example:
```bash
markoc . --clean
```
Alternatively, you can use the JavaScript API to compile a module as shown in the following sample code:
```javascript
require('marko/compiler').compileFile(path, function(err, src) {
// Do something with the compiled output
});
```
### Sample Compiled Template
```javascript
exports.create = function(__helpers) {
var empty = __helpers.e,
notEmpty = __helpers.ne,
escapeXml = __helpers.x,
forEach = __helpers.f,
escapeXmlAttr = __helpers.xa;
return function render(data, out) {
out.w('Hello ' +
escapeXml(data.name) +
'! ');
if (notEmpty(data.colors)) {
out.w('
');
}
};
}
```
The compiled output is designed to be both extremely readable and minifiable. The minified code is shown below:
```javascript
exports.create=function(a){var d=a.ne,c=a.x,e=a.f,f=a.xa;return function(a,b){b.w("Hello "+c(a.name)+"! ");d(a.colors)?(b.w("
"),e(a.colors,function(a){b.w('
'+c(a)+"
")}),b.w("
")):b.w("
No colors!
")}};
```
_File size: 189 bytes gzipped (251 bytes uncompressed)_
## Hot reloading templates
During development it is very beneficial to not have to restart the server in order for changes to already loaded templates to be reflected. Marko supports hot reloading of templates on the server, but this feature must be explicitly enabled. Enabling hot reloading is documented as part of the following sample app: [marko-js-samples/marko-hot-reload](https://github.com/marko-js-samples/marko-hot-reload)
# Language Guide
## Template Directives Overview
Almost all of the Marko templating directives can be used as either an attribute or as an element. For example:
_Applying directives using attributes:_
```xml
$color
No colors!
```
_Applying directives using elements:_
```xml
$color
No colors!
```
The disadvantage of using elements to control structural logic is that they change the nesting of the elements which can impact readability. For this reason it is often more suitable to apply directives as attributes.
## Text Replacement
Dynamic text is supported using either `$` or `${}`.
Examples:
```xml
Hello $data.name!
Hello ${data.name}!
Hello ${data.name.toUpperCase()}!
```
By default, all special HTML characters will be escaped in dynamic text to prevent Cross-site Scripting (XSS) Attacks. To disable HTML escaping, you can use `$!` as shown in the following sample code:
```xml
Hello $!{data.name}!
```
If necessary, you can escape `$` using a forward slash to have it be treated as text instead of a placeholder token:
```xml
Test: \${hello}
```
## Expressions
Wherever expressions are allowed, they are treated as JavaScript expressions and copied out to the compiled template verbatim. However, you can choose to use alternate versions of the following JavaScript operators:
JavaScript Operator | Marko Equivalent
------------------- | -----------------
`&&` | `and`
|| | `or`
`===` | `eq`
`!==` | `ne`
`<` | `lt`
`>` | `gt`
`<=` | `le`
`>=` | `ge`
For example, both of the following are valid and equivalent:
```xml
Show More
```
```xml
Show More
```
## Includes
Marko supports includes/partials. Other Marko files can be included using the `` tag and a relative path. For example:
```xml
```
Alternatively, you can pass the template data using the `template-data` attribute whose value should be a JavaScript expression that resolves to the template data as shown below:
```xml
```
The value of the `template` attribute can also be a dynamic JavaScript expression that resolves to a loaded template as shown below:
In your JavaScript controller:
```javascript
var myIncludeTarget = require('./my-include-target.marko');
var anotherIncludeTarget = require('./another-include-target.marko');
template.render({
myIncludeTarget: myIncludeTarget,
anotherIncludeTarget: anotherIncludeTarget
},
...);
```
And then in your template:
```xml
```
You can also choose to load the include target within the calling template as shown below:
```xml
...
```
## Variables
Input data passed to a template is made available using a special `data` variable. It's possible to declare your own variables as shown in the following sample code:
```xml
```
To assign a new value to an existing variable the `` tag can be used as shown in the following sample code:
```xml
```
The `` directive can be used to create scoped variables as shown in the following sample code:
```xml
Hello $nameUpper!
Hello $nameLower!
```
## Conditionals
### if...else-if...else
Any element or fragment of HTML can be made conditional using the `if`, `else-if` or `else` directive.
_Applied as attributes:_
```xml
Hello World
A
B
C
Something else
```
_Applied as elements:_
```xml
Hello World
A
B
C
Something else
```
### Shorthand Conditionals
Shorthand conditionals allow for conditional values inside attributes or wherever expressions are allowed. Shorthand conditionals are of the following form:
`{?;[;]}`
For example:
```xml
Hello
```
With a value of `true` for `active`, the output would be the following:
```xml
Hello
```
With a value of `false` for `active`, the output would be the following:
```xml
Hello
```
_NOTE: If the expression inside an attribute evaluates to `null` or an empty string then the attribute is not included in the output._
As shown in the previous example, the "else" block for shorthand conditionals is optional. The usage of an else block is shown below:
```xml
Hello
```
With a value of `false` for `active`, the output would be the following:
```xml
Hello
```
### Conditional Attributes
Marko supports conditional attributes when the value of an attribute is an expression. Marko also supports [HTML `boolean` attributes](https://html.spec.whatwg.org/#boolean-attributes) (e.g., ``) If an attribute value resolves to `null`, `undefined`, `false` or an empty string then the attribute will not be rendered. If an attribute value resolves to `true` then only the attribute name will rendered.
For example, given the following data:
```javascript
{
title: '',
active: true,
checked: false,
disabled: true
}
```
And the following template:
```xml
```
The output HTML will be the following:
```xml
```
## Looping
### for
Any element can be repeated for every item in an array using the `for` directive. The directive can be applied as an element or as an attribute.
_Applied as an attribute:_
```xml
${item}
```
_Applied as an element:_
```xml
${item}
```
Given the following value for items:
```javascript
["red", "green", "blue"]
```
The output would be the following:
```xml
red
green
blue
```
#### Loop Status Variable
The `for` directive also supports a loop status variable in case you need to know the current loop index. For example:
```xml
$color
${loop.getIndex()+1}) of ${loop.getLength()}
- FIRST - LAST
```
#### Loop Separator
```xml
$color
$color
```
#### Range Looping
A range can be provided in the following format; ` from to [ step ]`.
The `from`, `to` and `step` values must be numerical expressions. If not specified, step defaults to 1.
```xml
$i
```
```xml
$i
```
```xml
${myArray[i]}
```
#### Property Looping
```xml
$name:
$value
```
#### Custom Iterator
A custom iterator function can be passed as part of the view model to the template to control looping over data.
A sample custom iterator function that loops over an array in reverse is shown below:
```javascript
{
reverseIterator: function(arrayList, callback) {
for(var i=arrayList.length-1; i>=0; i--){
callback(arrayList[i]);
}
}
}
```
The custom iterator can then be used in a template as shown below:
_Applied as part of a `for` attribute:_
```xml
$item
```
_Applied as part of a `` element:_
```xml
$item
```
Custom iterators also support providing a custom status object for each loop iteration:
```javascript
{
reverseIterator: function(arrayList, callback){
var statusVar = {first: 0, last: arrayList.length-1};
for(var i=arrayList.length-1; i>=0; i--){
statusVar.index = i;
callback(arrayList[i], statusVar);
}
}
}
```
_Applied as part of a `for` attribute:_
```xml
${status.index}$item
```
_Applied as part of a `` element:_
```xml
${status.index}$item
```
## Macros
Parameterized macros allow for reusable fragments within an HTML template. A macro can be defined using the `` directive.
### def
The `` directive can be used to define a reusable function within a template.
```xml
Hello $name! You have $count new messages.
```
The above macro can then be invoked as part of any expression. Alternatively, the [``](#invoke) directive can be used invoke a macro function using named attributes. The following sample template shows how to use macro functions inside expressions:
```xml
Hello $name! You have $count new messages.
${greeting("John", 10)}
${greeting("Frank", 20)}
```
### invoke
The `` directive can be used to invoke a function defined using the `` directive or a function that is part of the input data to a template. The `` directive allows arguments to be passed using element attributes, but that format is only supported for functions that were previously defined using the `` directive.
```xml
Hello ${name}! You have ${count} new messages.
```
The output for the above template would be the following:
```xml
Hello John! You have 10 new messages.
Hello Frank! You have 20 new messages.
```
_NOTE:_ By default, the arguments will be of type "string" when using `.` However, argument attributes support JavaScript expressions which allow for other types of arguments. Example:
```xml
count="10"
count="${10}"
```
## Structure Manipulation
### attrs
The `attrs` attribute allows attributes to be dynamically added to an element at runtime. The value of the attrs attribute should be an expression that resolves to an object with properties that correspond to the dynamic attributes. For example:
```xml
Hello World!
```
Given the following value for the `myAttrs` variable:
```javascript
{style: "background-color: #FF0000;", "class": "my-div"}
```
The output would then be the following:
```xml
Hello World!
```
### body-only-if
If you find that you have a wrapper element that is conditional, but whose body should always be rendered then you can use the `body-only-if` attribute to handle this use case. For example, to only render a wrapping `` tag if there is a valid URL then you could do the following:
```xml
Some body content
```
Given a value of `"http://localhost/"` for the `data.linkUrl` variable: , the output would be the following:
```xml
Some body content
```
Given a value of `undefined` for the `data.linkUrl` variable: , the output would be the following:
```xml
Some body content
```
## Comments
Standard HTML comments can be used to add comments to your template. The HTML comments will not show up in the rendered HTML.
Example comments:
```xml
Hello
```
If you would like for your HTML comment to show up in the final output then you can use the custom `html-comment` tag:
```xml
This is a comment that *will* be rendered
Hello
```
Output:
```xml
Hello
```
## Whitespace
The Marko compiler will remove unnecessary whitespace based on some builtin rules, by default. These rules are partially based on the rules that browser's use to normalize whitespace and partially based on the goal of allowing nicely indented markup with minified output. These rules are as follows:
- For text before the first child element: `text.replace(/^\n\s*/g, '')`
- For text after the last child element: `text.replace(/\n\s*$/g, '')`
- For text between child elements: `text.replace(/^\n\s*$/g, '')`
- Any contiguous sequence of whitespace characters is collapsed into a single space character
In addition, whitespace within the following tags is preserved by default:
- `