Rdoc.info Slim (1)

28
rdoc.info http://rdoc.info/github/stonean/slim Slim Slim is a template language whose goal is to reduce the view syntax to the essential parts without becoming cryptic. It started as an exercise to see how much could be removed from a standard html template (<, >, closing tags, etc...). As more people took an interest in Slim, the functionality grew and so did the flexibility of the syntax. A short list of the features... Short syntax without closing tags (Using indentation instead) Embedded engines like Markdown and Textile Configurable shortcut tags (# for div id and . for div class in the default configuration) Automatic HTML escaping and support for Rails' html_safe? HTML style mode with closing tags Logic less mode similar to Mustache, realized as plugin Translator/I18n, realized as plugin Highly configurable and extendable High performance (Comparable to ERB) Supported by all major frameworks (Rails, Sinatra, ...) Streaming support in Rails Introduction What is Slim? Slim is a fast, lightweight templating engine with support for Rails 3. It has been heavily tested on all major ruby implementations. We use continous integration (travis-ci). Slim's core syntax is guided by one thought: "What's the minimum required to make this work". As more people have contributed to Slim, there have been syntax additions influenced from their use of Haml and Jade. The Slim team is open to these additions because we know beauty is in the eye of the beholder. Slim uses Temple for parsing/compilation and is also integrated into T ilt , so it can be used together

Transcript of Rdoc.info Slim (1)

Page 1: Rdoc.info Slim (1)

rdoc.info http://rdoc.info/github/stonean/slim

Slim

Slim is a template language whose goal is to reduce the view syntax to theessent ial parts without becoming crypt ic. It started as an exercise to see howmuch could be removed from a standard html template (<, >, closing tags,etc...). As more people took an interest in Slim, the funct ionality grew and sodid the f lexibility of the syntax.

A short list of the features...

Short syntax without closing tags (Using indentat ion instead)

Embedded engines like Markdown and Text ile

Conf igurable shortcut tags (# for div id and . for div class in the default conf igurat ion)

Automat ic HTML escaping and support for Rails' html_safe?

HTML style mode with closing tags

Logic less mode similar to Mustache, realized as plugin

Translator/I18n, realized as plugin

Highly conf igurable and extendable

High performance (Comparable to ERB)

Supported by all major f rameworks (Rails, Sinatra, ...)

Streaming support in Rails

Introduction

What is Slim?

Slim is a fast , lightweight templat ing engine with support for Rails 3. It has been heavily tested onall major ruby implementat ions. We use cont inous integrat ion (t ravis-ci).

Slim's core syntax is guided by one thought: "What 's the minimum required to make this work".

As more people have contributed to Slim, there have been syntax addit ions inf luenced from theiruse of Haml and Jade. The Slim team is open to these addit ions because we know beauty is in theeye of the beholder.

Slim uses Temple for parsing/compilat ion and is also integrated into Tilt , so it can be used together

Page 2: Rdoc.info Slim (1)

with Sinatra or plain Rack.

The architecture of Temple is very f lexible and allows the extension of the parsing and compilat ionprocess without monkey-patching. This is used by the logic less plugin and the translator pluginwhich provides I18n.

Why use Slim?

Within the Rails community, Erb and Haml are without doubt the two most popular templat ingengines. However, Erb's syntax is cumbersome and Haml's syntax can be quite crypt ic to theuninit iated.

Slim was born to bring a minimalist syntax approach with speed. If people chose not to use Slim, itwould not be because of speed.

Yes, Slim is speedy! Benchmarks are provided at the end of this README f ile. Don't t rust thenumbers? That 's as it should be. Therefore we provide a benchmark rake task so you could test ityourself (rake bench).

How to start?

Install Slim as a gem:

gem install sl im

Include Slim in your Gemfile with gem 'sl im' or require it with require 'sl im' . That 's it ! Now, justuse the .slim extension and you're good to go.

Syntax example

Here's a quick example to demonstrate what a Slim template looks like:

Page 3: Rdoc.info Slim (1)

doctype htmlhtml head title Slim Examples meta name="keywords" content="template language" meta name="author" content=author l ink rel="icon" type="image/png" href=file_path("favicon.png") javascript: alert('Sl im supports embedded javascript!')

body h1 Markup examples

#content p This example shows you how a basic Slim fi le looks l ike.

= yield

- i f items.any? table#items - for item in items do tr td.name = item.name td.price = item.price - else p No items found Please add some inventory. Thank you!

div id="footer" = render 'footer' | Copyright &copy; #{year} #{author}

Indentat ion matters, but the indentat ion depth can be chosen as you like. If you want to f irstindent 2 spaces, then 5 spaces, it 's your choice. To nest markup you only need to indent by onespace, the rest is gravy.

Line indicators

Text |

The pipe tells Slim to just copy the line. It essent ially escapes any processing. Each following linethat is indented greater than the backt ick is copied over.

body p | This is a test of the text block.

Page 4: Rdoc.info Slim (1)

The parsed result of the above:

<body><p>This is a test of the text block.</p></body>

The lef t margin is set at the indent of the backt ick + one space. Any addit ional spaces will becopied over.

body p | This l ine is on the left margin. This l ine wil l have one space in front of it. This l ine wil l have two spaces in front of it. And so on...

You can also embed html in the text line

- articles.each do |a| | <tr><td>#{a.name}</td><td>#{a.description}</td></tr>

Text with trailing white space '

The single quote tells Slim to copy the line (similar to |), but makes sure that a single t railing whitespace is appended.

Inline html < (HTML style)

You can write html tags direct ly in Slim which allows you to write your templates in a more html likestyle with closing tags or mix html and Slim style.

<html> head title Example <body> - i f articles.empty? - else table - articles.each do |a| <tr><td>#{a.name}</td><td>#{a.description}</td></tr> </body></html>

Page 5: Rdoc.info Slim (1)

Control code -

The dash denotes control code. Examples of control code are loops and condit ionals. end isforbidden behind -. Blocks are def ined only by indentat ion. If your ruby code needs to use mult iplelines, append a backslash \ at the end of the lines.

body - i f articles.empty? | No inventory

Output =

The equal sign tells Slim it 's a Ruby call that produces output to add to the buffer. If your rubycode needs to use mult iple lines, append a backslash \ at the end of the lines, for example:

= javascript_include_tag \ " jquery", \ "application"

Output with trailing white space ='

Same as the single equal sign (=), except that it adds a t railing white space.

Output without HTML escaping ==

Same as the single equal sign (=), but does not go through the escape_html method.

Output without HTML escaping and trailing ws =='

Same as the double equal sign (==), except that it adds a t railing white space.

Use the forward slash for code comments - anything af ter it won't get displayed in the f inal render.Use / for code comments and /! for html comments

body p / This l ine won't get displayed. Neither does this l ine. /! This wil l get displayed as html comments.

The parsed result of the above:

Page 6: Rdoc.info Slim (1)

<body><p><!--This wil l get displayed as html comments.--></p></body>

Use the forward slash immediately followed by an exclamat ion mark for html comments (<!-- ... -->).

/[if IE]

renders as

<!--[if IE]><p>Get a better browser.</p><![endif]-->

Doctype tag

The doctype tag is a special tag which can be used to generate the complex doctypes in a verysimple way.

XML VERSION

doctype xml <?xml version="1.0" encoding="utf-8" ?>

doctype xml ISO-8859-1 <?xml version="1.0" encoding="iso-8859-1" ?>

XHTML DOCTYPES

Page 7: Rdoc.info Slim (1)

doctype html <!DOCTYPE html>

doctype 5 <!DOCTYPE html>

doctype 1.1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

doctype strict <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

doctype frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">

doctype mobile <!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobileall iance.org/tech/DTD/xhtml-mobile12.dtd">

doctype basic <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">

doctype transitional <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

HTML 4 DOCTYPES

doctype strict <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

doctype frameset <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">

doctype transitional <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

You can close tags explicit ly by appending a t railing /.

img src="image.png"/

Page 8: Rdoc.info Slim (1)

Note, that this is usually not necessary since the standard html tags (img, br, ...) are closedautomat ically.

Sometimes you may want to be a lit t le more compact and inline the tags.

ul l i .first: a href="/a" A l ink l i : a href="/b" B l ink

For readability, don't forget you can wrap the at t ributes.

ul l i .first: a[href="/a"] A l ink l i : a[href="/b"] B l ink

Text content

Either start on the same line as the tag

body h1 id="headline" Welcome to my site.

Or nest it . You must use a pipe or a backt ick to escape processing

body h1 id="headline" | Welcome to my site.

Dynamic content (= and ==)

Can make the call on the same line

body h1 id="headline" = page_headline

Or nest it .

Page 9: Rdoc.info Slim (1)

body h1 id="headline" = page_headline

Attributes

You write at t ributes direct ly af ter the tag. For normal text at t ributes you must use double " orsingle quotes ' (Quoted at t ributes).

a href="http://sl im-lang.com" title='Slim Homepage' Goto the Slim homepage

You can use text interpolat ion in the quoted at t ributes.

Attributes wrapper

If a delimiter makes the syntax more readable for you, you can use the characters {...}, (...), [...]to wrap the at t ributes.

body h1(id="logo") = page_logo h2[id="tagline" class="small tagline"] = page_tagline

If you wrap the at t ributes, you can spread them across mult iple lines:

h2[id="tagline" class="small tagline"] = page_tagline

Quoted attributes

Example:

a href="http://sl im-lang.com" title='Slim Homepage' Goto the Slim homepage

You can use text interpolat ion in the quoted at t ributes:

a href="http://#{url}" Goto the #{url}

The at t ribute value will be escaped if the opt ion :escape_quoted_attrs is set . Use == if you wantto disable escaping in the at t ribute.

Page 10: Rdoc.info Slim (1)

a href=="&amp;"

Ruby attributes

Write the ruby code direct ly af ter the =. If the code contains spaces you have to wrap the codeinto parentheses (...), {...} or [...]. The code in the parentheses will be evaluated.

body table - for user in users do td id="user_#{user.id}" class=user.role a href=user_action(user, :edit) Edit #{user.name} a href={path_to_user user} = user.name

The at t ribute value will be escaped by default . Use == if you want to disable escaping in theattribute.

a href==action_path(:start)

Boolean attributes

The at t ribute values true, false and nil are interpreted as booleans. If you use the at t ributwrapper you can omit the at t ribute assigment

input type="text" disabled="disabled"input type="text" disabled=trueinput(type="text" disabled)

input type="text"input type="text" disabled=falseinput type="text" disabled=nil

Attribute merging

You can conf igure at t ributes to be merged if mult iple are given (See opt ion :attr_delimiter). Inthe default conf igurat ion this is done for class at t ributes with the white space as delimiter.

a.menu class="highlight" href="http://sl im-lang.com/" Slim-lang.com

Page 11: Rdoc.info Slim (1)

This renders as

<a class="menu highlight" href="http://sl im-lang.com/">Slim-lang.com</a>

You can also use an Array as at t ribute value and the array elements will be merged using thedelimiter.

a class=["menu","highlight"]a class=:menu,:highlight

Splat attributes *

The splat shortcut allows you turn a hash in to at t ribute/value pairs

.card*{'data-url '=>place_path(place), 'data-id'=>place.id} = place.name

renders as

<div class="card" data-id="1234" data-url="/place/1234">Slim's house</div>

You can also use methods or instance variables which return a hash as shown here:

.card *method_which_returns_hash = place.name

.card *@hash_instance_variable = place.name

The hash at t ributes which support at t ribute merging (see Slim opt ion :attr_delimiter) can begiven as an Array

.first *{:class => [:second, :third]} Text

renders as

div class="first second third"

ID shortcut # and class shortcut .

Page 12: Rdoc.info Slim (1)

Similarly to Haml, you can specify the id and class at t ributes in the following shortcut form

body h1#headline = page_headline h2#tagline.small.tagline = page_tagline .content = show_content

This is the same as

body h1 id="headline" = page_headline h2 id="tagline" class="small tagline" = page_tagline div class="content" = show_content

Attribute shortcuts

You can def ine custom shortcuts (Similar to # for id and . for class).

In this example we add & to create a shortcut for the input elements with type at t ribute.

Slim::Engine.set_default_options :shortcut => {'&' => ' input type', '#' => ' id', ' .' => 'class'}

We can use it in Slim code like this

&text name="user"&password name="pw"&submit

which renders to

<input type="text" name="user" /><input type="password" name="pw" /><input type="submit" />

Page 13: Rdoc.info Slim (1)

In another example we add @ to create a shortcut for the role at t ribute.

Slim::Engine.set_default_options :shortcut => {'@' => 'role', '#' => ' id', ' .' => 'class'}

We can use it in Slim code like this

.person@admin = person.name

which renders to

<div class="person" role="admin">Daniel</div>

Text interpolation

Use standard Ruby interpolat ion. The text will be html escaped by default .

body h1 Welcome #{current_user.name} to the show. | Unescaped #{{content}} is also possible.

To escape the interpolat ion (i.e. render as is)

body h1 Welcome \#{current_user.name} to the show.

Embedded engines (Markdown, ...)

Thanks to Tilt , Slim has impressive support for embedding other template engines.

Examples:

coffee: square = (x) -> x * x

markdown: #Header Hello from #{"Markdown!"} Second Line!

Page 14: Rdoc.info Slim (1)

Supported engines:

Filter Required gems Type Descript ion

ruby: none Shortcut Shortcut to embed rubycode

javascript : none Shortcut Shortcut to embedjavascript code and wrapin script tag

css: none Shortcut Shortcut to embed csscode and wrap in style tag

sass: sass Compilet ime

Embed sass code andwrap in style tag

scss: sass Compilet ime

Embedd scss code andwrap in style tag

less: less Compilet ime

Embed less css code andwrap in style tag

styl: styl Compilet ime

Embed stylus css codeand wrap in style tag

coffee: coffee-script Compilet ime

Compile cof fee scriptcode and wrap in scripttag

markdown: redcarpet/rdiscount/kramdown Compilet ime +Interpolat ion

Compile markdown codeand interpolate# {variables} in text

text ile: redcloth Compilet ime +Interpolat ion

Compile text ile code andinterpolate # {variables} intext

creole: creole Compilet ime +Interpolat ion

Compile creole code andinterpolate # {variables} intext

Page 15: Rdoc.info Slim (1)

wiki:,mediawiki:

wikicloth Compilet ime +Interpolat ion

Compile wiki code andinterpolate # {variables} intext

rdoc: rdoc Compilet ime +Interpolat ion

Compile rdoc code andinterpolate # {variables} intext

builder: builder Precompiled Embed builder code

nokogiri: nokogiri Precompiled Embed nokogiri buildercode

erb: none Precompiled Embed erb code

The embedded engines can be conf igured in Slim by sett ing the opt ions direct ly on the Slim::EmbeddedEngine f ilter. Example:

Slim::EmbeddedEngine.default_options[:markdown] = {:auto_ids => false}

Configuring Slim

Slim and the underlying Temple f ramework are highly conf igurable. The way how you conf igureSlim depends a bit on the compilat ion mechanism (Rails or Tilt ). It is always possible to set defaultopt ions per Slim::Engine class. This can be done in Rails' environment f iles. For instance, inconf ig/environments/development.rb you probably want:

Default options

Slim::Engine.set_default_options :pretty => true, :sort_attrs => false

Slim::Engine.set_default_options pretty: true, sort_attrs: false

You can also access the opt ion hash direct ly:

Slim::Engine.default_options[:pretty] = true

Setting options at runtime

There are two ways to set opt ions at runt ime. For Tilt templates (Slim::Template) you can set

Page 16: Rdoc.info Slim (1)

the opt ions when you instat iate the template:

Slim::Template.new('template.sl im', optional_option_hash).render(scope)

The other possibility is to set the opt ions per thread which is interest ing most ly for Rails:

Slim::Engine.with_options(option_hash) do render :page, :layout => trueend

You have to be aware that the compiled engine code and the opt ions are cached per template inRails and you cannot change the opt ion af terwards.

Slim::Engine.with_options(:pretty => true) do render :page, :layout => trueend

Slim::Engine.with_options(:pretty => false) do render :page, :layout => true end

Available options

The following opt ions are exposed by the Slim::Engine and can be set with Slim::Engine.set_default_options. There are a lot of them but the good thing is, that Slimchecks the conf igurat ion keys and reports an error if you try to use an invalid conf igurat ion key.

Type Name Default

String :f ile nil

Integer :tabsize 4

String :encoding "ut f -8"

Page 17: Rdoc.info Slim (1)

String :default_tag "div"

Hash :shortcut {'.' => 'class', '# ' => 'id'}

Symbol/Stringlist

:enable_engines nil (All enabled)

Symbol/Stringlist

:disable_engines nil (None disabled)

Boolean :disable_capture false (t rue in Rails)

Boolean :disable_escape false

Boolean :escape_quoted_attrs false

Boolean :use_html_safe false (t rue in Rails)

Symbol :format :xhtml

String :at t r_wrapper '"'

Page 18: Rdoc.info Slim (1)

Hash :at t r_delimiter {'class' => ' '}

Boolean :sort_attrs true

Boolean :pret ty false

String :indent ' '

Boolean :streaming false (t rue in Rails > 3.1)

Class :generator Temple::Generators::ArrayBuffer/RailsOutputBuffer

String :buffer '_buf ' ('@output_buffer' in Rails)

There are more opt ions which are supported by the Temple f ilters but which are not exposed andare not of f icially supported. You have to take a look at the Slim and Temple code for that .

Option priority and inheritance

For developers who know more about Slim and Temple architecture it is possible to overridedefault opt ions at dif ferent posit ions. Temple uses an inheritance mechanism to allow subclassesto override opt ions of the superclass. The opt ion priorit ies are as follows:

1. Slim::Template opt ions passed at engine instat inat ion

2. Slim::Template.default_options

3. Slim::Engine.thread_options, Slim::Engine.default_options

4. Parser/Filter/Generator thread_options, default_options (e.g Slim::Parser, Slim::Compiler)

Page 19: Rdoc.info Slim (1)

It is also possible to set opt ions for superclasses like Temple::Engine. But this will af fect alltemple template engines then.

Slim::Engine < Temple::EngineSlim::Compiler < Temple::Fi lter

Plugins

Logic less mode

Logic less mode is inspired by Mustache. Logic less mode uses a dict ionary object e.g. a recursivehash tree which contains the dynamic content.

Conditional

If the object is not false or empty?, the content will show

- article h1 = title

Inverted conditional

If the object is false or empty?, the content will show

-! article p Sorry, article not found

Iteration

If the object is an array, the sect ion will iterate

- articles tr: td = title

Wrapped dictionary - Resolution order

Example code:

Page 20: Rdoc.info Slim (1)

- article h1 = title

In wrapped dict ionary acccess mode (the default , see the opt ions), the dict ionary object isaccessed in the following order.

1. If article.respond_to?(:title), Slim will execute article.send(:title)

2. If article.respond_to?(:has_key?) and article.has_key?(:title), Slim will execute article[:title]

3. If article.instance_variable_defined?(@title), Slim will execute article.instance_variable_get @title

If all the above fails, Slim will t ry to resolve the t it le reference in the same order against the parentobject . In this example, the parent would be the dict ionary object you are rendering the templateagainst .

As you might have guessed, the art icle reference goes through the same steps against thedict ionary. Instance variables are not allowed in the view code, but Slim will f ind and use them.Essent ially, you're just using dropping the @ pref ix in your template. Parameterized method callsare not allowed.

Logic less in Rails

Install:

$ gem install sl im

Require:

gem 'sl im', :require => 'sl im/logic_less'

You might want to act ivate logic less mode only for a few act ions, you should disable logic-lessmode globally at f irst in the conf igurat ion

Slim::Engine.set_default_options :logic_less => false

and act ivate logic less mode per render call in your act ion

Page 21: Rdoc.info Slim (1)

class Controller def action Sl im::Engine.with_options(:logic_less => true) do render end endend

Logic less in Sinatra

Sinata has built -in support for Slim. All you have to do is require the logic less Slim plugin. This canbe done in your conf ig.ru:

require 'sl im/logic_less'

You are then ready to rock!

You might want to act ivate logic less mode only for a few act ions, you should disable logic-lessmode globally at f irst in the conf igurat ion

Slim::Engine.set_default_options :logic_less => false

and act ivate logic less mode per render call in your applicat ion

get ' /page' sl im :page, :logic_less => trueend

Options

Type Name Default Purpose

Boolean :logic_less true Enable logic less mode (Enabled if'slim/logic_less' is required)

String :dict ionary "self" Dict ionary where variables are looked up

Symbol :dict ionary_access :wrapped Dict ionary access mode (:string, :symbol,:wrapped)

Page 22: Rdoc.info Slim (1)

Translator/I18n

The translator plugin provides automat ic t ranslat ion of the templates using Gettext , Fast-Gettextor Rails I18n. Stat ic text in the template is replaced by the translated version.

Example:

h1 Welcome to

Gettext t ranslates the string f rom english to german where interpolat ions are replaced by %1, %2,...

"Welcome to %1!" -> "Willkommen auf %1!"

and renders as

<h1>Willkommen auf sl im-lang.com!</h1>

Enable the translator plugin with

require 'sl im/translator'

Options

Type Name Default Purpose

Boolean :tr t rue Enable t ranslator (Enabled if'slim/translator' is required)

Symbol :t r_mode :dynamic When to t ranslate: :stat ic = at compilet ime, :dynamic = at runt ime

String :t r_fn Depending on installedtranslat ion library

Translat ion funct ion, could be '_' forgettext

Framework support

Tilt

Page 23: Rdoc.info Slim (1)

Slim uses Tilt to compile the generated code. If you want to use the Slim template direct ly, you canuse the Tilt interface.

Tilt.new['template.sl im'].render(scope)Slim::Template.new('template.sl im', optional_option_hash).render(scope)Slim::Template.new(optional_option_hash) { source }.render(scope)

The opt ional opt ion hash can have to opt ions which were documented in the sect ion above.

Sinatra

require 'sinatra'require 'sl im'

get('/') { sl im :index }

__END__@@ indexdoctype htmlhtml head title Sinatra With Slim body h1 Slim Is Fun!

Rails

Rails generators are provided by slim-rails. slim-rails is not necessary to use Slim in Rails though.Just install Slim and add it to your Gemfile with gem 'sl im' . Then just use the .slim extension andyou're good to go.

Streaming

HTTP streaming is enabled enabled by default if you use a Rails version which supports it .

Tools

Slim Command 'slimrb'

The gem 'slim' comes with the small tool 'slimrb' to test Slim from the command line.

Page 24: Rdoc.info Slim (1)

$ slimrb --helpUsage: sl imrb [options] -s, --stdin Read input from standard input instead of an input fi le --trace Show a full traceback on error -c, --compile Compile only but do not run -r, --rails Generate rails compatible code (Implies --compile) -t, --translator Enable translator plugin -l , --logic-less Enable logic less plugin -p, --pretty Produce pretty html -o, --option [NAME=CODE] Set sl im option -h, --help Show this message -v, --version Print version

Start 'slimrb', type your code and press Ctrl-d to send EOF. Example usage:

$ slimrbmarkdown: First paragraph.

Second paragraph.

* one * two * three

//Enter Ctrl-d<p>First paragraph </p>

<p>Second paragraph </p>

<ul><li>one</li><li>two</li><li>three</li></ul>

Syntax Highlighters

There are plugins for various text editors (including the most important ones - Vim, Emacs andTextmate):

Vim

Emacs

Textmate / Sublime Text

Page 25: Rdoc.info Slim (1)

Espresso text editor

Coda

Template Converters (HAML, ERB, ...)

Haml2Slim converter

HTML2Slim converter

ERB2Slim converter

Testing

Benchmarks

The benchmarks demonstrate that Slim in production mode is nearly as fast as Erubis (which is thefastest template engine). So if you choose not to use Slim it is not due to its speed.

Run the benchmarks with rake bench. You can add the opt ion slow to run the slow parsingbenchmark which needs more t ime. You can also increase the number of iterat ions.

rake bench slow=1 iterations=1000

Linux + Ruby 1.9.3, 1000 iterations

user system total real(1) erb 0.020000 0.000000 0.020000 ( 0.017383)(1) erubis 0.020000 0.000000 0.020000 ( 0.015048)(1) fast erubis 0.020000 0.000000 0.020000 ( 0.015372) <===(1) temple erb 0.030000 0.000000 0.030000 ( 0.026239)(1) sl im pretty 0.030000 0.000000 0.030000 ( 0.031463)(1) sl im ugly 0.020000 0.000000 0.020000 ( 0.018868) <===(1) haml pretty 0.130000 0.000000 0.130000 ( 0.122521)(1) haml ugly 0.110000 0.000000 0.110000 ( 0.106640)(2) erb 0.030000 0.000000 0.030000 ( 0.035520)(2) erubis 0.020000 0.000000 0.020000 ( 0.023070)(2) temple erb 0.040000 0.000000 0.040000 ( 0.036514)(2) sl im pretty 0.040000 0.000000 0.040000 ( 0.040086)(2) sl im ugly 0.030000 0.000000 0.030000 ( 0.028461)(2) haml pretty 0.150000 0.000000 0.150000 ( 0.145618)(2) haml ugly 0.130000 0.000000 0.130000 ( 0.129492)(3) erb 0.140000 0.000000 0.140000 ( 0.134953)(3) erubis 0.120000 0.000000 0.120000 ( 0.119723)(3) fast erubis 0.100000 0.000000 0.100000 ( 0.097456)(3) temple erb 0.040000 0.000000 0.040000 ( 0.035916)(3) sl im pretty 0.040000 0.000000 0.040000 ( 0.039626)

Page 26: Rdoc.info Slim (1)

(3) sl im ugly 0.030000 0.000000 0.030000 ( 0.027827)(3) haml pretty 0.310000 0.000000 0.310000 ( 0.306664)(3) haml ugly 0.250000 0.000000 0.250000 ( 0.248742)(4) erb 0.350000 0.000000 0.350000 ( 0.350719)(4) erubis 0.310000 0.000000 0.310000 ( 0.304832)(4) fast erubis 0.300000 0.000000 0.300000 ( 0.303070)(4) temple erb 0.910000 0.000000 0.910000 ( 0.911745)(4) sl im pretty 3.410000 0.000000 3.410000 ( 3.413267)(4) sl im ugly 2.880000 0.000000 2.880000 ( 2.885265)(4) haml pretty 2.280000 0.000000 2.280000 ( 2.292623)(4) haml ugly 2.170000 0.000000 2.170000 ( 2.169292)

(1) Compiled benchmark. Template is parsed before the benchmark and generated ruby code is compiled into a method. This is the fastest evaluation strategy because it benchmarks pure execution speed of the generated ruby code.

(2) Compiled Tilt benchmark. Template is compiled with Tilt, which gives a more accurate result of the performance in production mode in frameworks l ike Sinatra, Ramaze and Camping. (Rails sti l l uses its own template compilation.)

(3) Cached benchmark. Template is parsed before the benchmark. The ruby code generated by the template engine might be evaluated every time. This benchmark uses the standard API of the template engine.

(4) Parsing benchmark. Template is parsed every time. This is not the recommended way to use the template engine and Slim is not optimized for it. Activate this benchmark with 'rake bench slow=1'.

Temple ERB is the ERB implementation using the Temple framework. It shows theoverhead added by the Temple framework compared to ERB.

Test suite and continous integration

Slim provides an extensive test-suite based on minitest . You can run the tests with 'rake test ' andthe rails integrat ion tests with 'rake test :rails'.

We are current ly experiment ing with human-readable literate tests which are writ ten as markdownf iles: TESTS.md

Travis-CI is used for cont inous integrat ion test ing: ht tp://t ravis-ci.org/# !/stonean/slim

Slim is working well on all major Ruby implementat ions:

Ruby 1.8.7

Ruby 1.9.2

Page 27: Rdoc.info Slim (1)

Ruby 1.9.3

Ruby EE

JRuby

Rubinius 2.0

Contributing

If you'd like to help improve Slim, clone the project with Git by running:

$ git clone git://github.com/stonean/slim

Work your magic and then submit a pull request. We love pull requests!

Please remember to test against Ruby versions 1.9.2 and 1.8.7.

If you f ind the documentat ion lacking (and you probably will), help us out The docs are located inthe gh-pages branch:

$ git checkout gh-pages

If you don't have the t ime to work on Slim, but found something we should know about, pleasesubmit an issue.

License

Slim is released under the MIT license.

Authors

Andrew Stone

Fred Wu

Daniel Mendler

Discuss

Google Group

IRC Channel #slim-lang on freenode.net

Related projects

Page 28: Rdoc.info Slim (1)

Template compilat ion f ramework:

Temple

Framework support :

Rails 3 generators (slim-rails)

Syntax highlight ing:

Vim

Emacs

Textmate / Sublime Text

Espresso text editor

Coda

Template Converters (HAML, ERB, ...):

Haml2Slim converter

HTML2Slim converter

ERB2Slim converter

Language ports/Similar languages:

Coffee script plugin for Slim

Clojure port of Slim

Hamlet.rb (Similar template language)

Plim (Python port of Slim)

Skim (Slim for Javascript)

Haml (Older engine which inspired Slim)

Jade (Similar engine for javascript)