Search code examples
ruby-on-railsrubyslim-lang

variables in slim rails


I have template written with Slim, and I want to use it with Ruby but I have these errors in index.slim.

   -content_panel_file = '_partials/content_panel_5'
   -content_box_file = '_partials/content_box_2'
   - menu_file = '_partials/menu_side'
   = render  '_partials/template'

In template.slim:

.content-i
        .content-box
          == Slim::Template.new(content_box_file).render(Object.new, 'template_vars' => template_vars)

but it gave this error:

undefined local variable or method `content_box_file' for #<#<Class:0x00000003b28308>:0x00000003b685c0>
Did you mean?  content_for

Solution

  • The reason is your content_box_file doesn't exist in your partial file, you're trying to access a local variable that's not in the current "scope".

    Try passing your content_box_file variable as a local one within your render method:

    = render partial: '_partials/template', locals: { content_box_file: content_box_file }
    

    Note you need to use render partial: ....

    Complete workflow:

    # model/index.html.slim
    - content_box_file = 'app/views/_partials/content_box_2.slim'
    = render partial: '_partials/template', locals: { content_box_file: content_box_file }
    
    # _partials/_template.html.slim:
    - template_vars = 'Hallo'
    == Slim::Template.new(content_box_file).render(Object.new, template_vars: template_vars)
    
    # _partials/content_box_2.html.slim:
    == template_vars