Ismail Moghul
Ismail Moghul

Reputation: 2984

How to use Slim directly in ruby

I would like to create a basic ruby script that renders Slim templates into html (This would eventually be part of a larger project). Ideally I would like to use the HTML produced within the script.

I understand this is possible using TILT (as shown in the SLIM README) where it says the following:


Slim uses Tilt to compile the generated code. If you want to use the Slim template directly, you can use the Tilt interface.

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

The optional option hash can have to options which were documented in the section above. The scope is the object in which the template code is executed.


However, I'm still unable to successfully run this. Therefore, I was wondering if someone could help me by producing a working example.

EDIT (this has recently been edited further ):

I have played about with the code quite a bit but I keep on getting the following error:

 undefined local variable or method `source' for main:Object (NameError)

This is what i'm running:

require 'slim'

# I'm not sure about the next two lines...
optional_option_hash = {}
scope = Object.new    

Tilt.new('template.slim').render(scope)
Slim::Template.new('template.slim', optional_option_hash).render(scope)
Slim::Template.new(optional_option_hash) { source }.render(scope)    

Many Thanks for all your help.

Upvotes: 3

Views: 3847

Answers (2)

Daniel Garmoshka
Daniel Garmoshka

Reputation: 6354

Quick essentials of

  module SlimRender

    def slim(template, variables = {})
      template = template.to_s
      template += '.slim' unless template.end_with? '.slim'
      template = File.read("#{ROOT}/app/views/#{template}", encoding: 'UTF-8')
      Slim::Template.new { template }.render OpenStruct.new(variables)
    end

  end

Include SlimRender to your class and:

  def render_something
    slim 'streams/scoreboard', scores: '1-2'
  end

Upvotes: 2

Ismail Moghul
Ismail Moghul

Reputation: 2984

See Specifying a layout and a template in a standalone (not rails) ruby app, using slim or haml

This is what I ended up using:

require 'slim'

# Simple class to represent an environment
class Env
  attr_accessor :name
end

scope = Env.new
scope.name = "test this layout"

layout =<<EOS
h1 Hello
.content
  = yield
EOS

contents =<<EOS
  = name
EOS

layout = Slim::Template.new { layout }
content = Slim::Template.new { contents }.render(scope)

puts layout.render{ content }

For the scope, you can put in modules/classes or even self.

Upvotes: 11

Related Questions