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
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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:
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!
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.
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>
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:
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.
a href=="&"
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
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.
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:
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"
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 '"'
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
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
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)
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
Slim uses Tilt to compile the generated code. If you want to use the Slim template direct ly, you canuse the Tilt interface.
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.
$ 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):
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.
(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: