Slim Template Engine

repository·main·Indexed 26 days ago

https://github.com/slim-template/slim

A high-performance, lightweight template language for Ruby that reduces view syntax to its essential parts using indentation instead of closing tags. Slim features shortcuts for IDs and classes, control code for Ruby logic, and support for embedding other engines via Tilt. It provides flexible options for handling verbatim text, whitespace management, and custom tag/attribute shortcuts.

Tokens
12.2K
Snippets
51
Records
91
Agent score
90%

What's inside Slim

  1. Mix text and markup with smart newline handling

    main

    The plugin manages whitespace when mixing text with inline tags (like a or strong).

    • Trailing Newline Suppression: A newline before a tag is suppressed if the preceding line ends with a character in :smart_text_end_chars (default: ([{).
    • Leading Newline Suppression: A newline after a tag is suppressed if the following line begins with a character in :smart_text_begin_chars (default: ,.;:!?)]}).

    Use the > indicator to distinguish lowercase text from tags when mixing them.

    # Natural mixing with punctuation
    p
      Please proceed to
      a href="/" our homepage
      .
    
    p
      Status: failed (
      a href="#1" see details
      ).
    
    # Mixing text and tags
    p
      Your credit card
      strong will not
      > be charged now.
  2. Use Logic-less Mode in Slim

    main

    Logic-less mode is inspired by Mustache and allows you to use dictionary objects (like recursive hash trees) for rendering content. It is enabled by default if you require slim/logic_less.

    Logic-less Syntax Features

    • Conditional Rendering: Content is displayed if the object is not false or empty?.
      - article
        h1 = title
    • Inverted Conditionals: Content is displayed if the object is false or empty? (using !).
      -! article
        p Sorry, article not found
    • Iteration: If the object is an array, the block is repeated for each element.
      - articles
        tr: td = title
    • Lambda Expressions: Supports Mustache-style lambdas. You can define a method that yields to a block, passing one or more hashes.
      def lambda_method
        "<div class='person'>#{yield(name: 'Andrew')}</div>"
      end
      And use it in Slim:
      = person
        = name
    - article
      h1 = title
    
    -! article
      p Sorry, article not found
    
    - articles
      tr: td = title
    
    = person
      = name
  3. Setup Logic less mode in Rails

    main

    To use Logic less mode in Rails, install the gem and require the logic-less extension. You can manage the mode globally or per-render call.

    1. Install:
    $ gem install slim
    1. Require in your application:
    gem 'slim', require: 'slim/logic_less'
    1. Control activation: To enable it only for specific actions, disable it globally first, then use Slim::Engine.with_options during the render call.
    # Disable globally
    Slim::Engine.set_options logic_less: false
    
    # Activate per render call
    class Controller
      def action
        Slim::Engine.with_options(logic_less: true) do
          render
        end
      end
    end
  4. Use Logic-less Mode in Rails

    main

    To use logic-less mode in a Rails application:

    1. Install the gem:
      gem install slim
    2. Require the logic-less extension in your Gemfile:
      gem 'slim', require: 'slim/logic_less'

    Enabling Logic-less Mode for Specific Actions

    If you want to disable logic-less mode globally and only enable it for specific actions, use Slim::Engine.with_options:

    class Controller
      def action
        Slim::Engine.with_options(logic_less: true) do
          render
        end
      end
    end
    gem 'slim', require: 'slim/logic_less'
  5. Merge attributes and use Splat attributes

    main

    Slim provides powerful ways to handle multiple or dynamic attributes.

    Attribute Merging If :merge_attrs is enabled, multiple class attributes are merged. You can also provide an Array as an attribute value to merge elements using the delimiter.

    Splat Attributes (*) The * shortcut turns a Hash into attribute/value pairs. This works with method calls or instance variables returning hashes.

    • Example: .card*{'data-url'=>path, 'data-id'=>id}.
    • For merging: .first *{class: [:second, :third]}.

    Dynamic Tags (*) You can create entirely dynamic tags by returning a hash with a :tag key from a method used with the splat operator.

  6. Slim Syntax Overview

    main

    Slim uses indentation to define nesting instead of closing tags. Key syntax features include:

    • Indentation: Determines nesting depth.
    • Shortcuts: # for IDs (e.g., #content becomes <div id="content">) and . for classes (e.g., td.name becomes <td class="name">).
    • Control Code (-): Used for Ruby logic like loops and conditionals. Blocks are defined by indentation, and end is forbidden after -.
    • Output (=): Executes Ruby code and adds the result to the buffer. Automatically escapes HTML.
    • Unescaped Output (==): Executes Ruby code and adds the result without HTML escaping.
    • Verbatim Text (|): Copies the line exactly as text, escaping Slim processing.
    doctype html
    html
      body
        h1 Title
        #content
          p Content with ID
        - if items.any?
          ul
            - for item in items
              li = item.name
        - else
          p No items
  7. Use Lambdas in Logic less mode

    main

    Slim supports lambdas in Logic less mode, similar to Mustache. You can define a lambda method that accepts a block via yield. You can optionally pass one or more hashes to yield to provide context to the block.

    def lambda_method
      "<div class='person'>#{yield(name: 'Andrew')}</div>"
    end

    Template usage:

    = person
      = name
  8. Enable the Slim Translator plugin

    main

    To use automatic template translation (converting static text within templates to translated versions), you must require the translator plugin in your application.

    The plugin supports Gettext, Fast-Gettext, or Rails I18n. When using Gettext, strings are converted from the source language (e.g., English) to the target language (e.g., German), and interpolation placeholders are converted to %1, %2, etc.

    Example conversion: h1 Welcome to #{url}! becomes <h1>Willkommen auf github.com/slim-template/slim!</h1> if the underlying library translates "Welcome to %1!" to "Willkommen auf %1!" and the URL is provided.

    require 'slim/translator'
  9. Capture template content to local variables

    main

    You can capture the output of a block into a local variable using Ruby's Binding. This is useful for storing rendered fragments for later use in the template.

    module Helpers
      def capture_to_local(var, &block)
        set_var = block.binding.eval("lambda {|x| #{var} = x }")
        set_var.call(defined?(::Rails) ? capture(&block) : yield)
      end
    end
    
    # Usage in Slim:
    # The variable must be known by the Binding beforehand.
    = capture_to_local captured_content=:captured_content
      p This will be captured in the variable captured_content
    = captured_content