Search code examples
ruby-on-railsrubyerbruby-on-rails-7

Can I nest a ruby embed symbol <%= %> inside another <%= %>


I want to use a helper Method inside link_to tag as follows

<%= link_to "Home", root_path, class:"nav-link <%= activeLink('home') %>" %>

This is my helper method

def activeLink(action_name)
    if controller.action_name == action_name
      "active"
    end
  end

I am getting error saying;

ActionView::SyntaxErrorInTemplate in PagesController#about

I want that helper method to check the current action name and set the 'active' CSS class if current action matches the input action name


Solution

  • Can you use nested <%= ... %> notation? No.

    However, what you're looking for is a form of string interpolation. As mentioned in the comments Ruby variables can be converted to strings in a couple ways (full details outlined in the linked guide).

    The primary method you'll see is by using #{} within a string ie "This is my string #{ruby_variable}".

    Which means you could use the following:

    my_string = "World!"
    
    hello_world_string = "Hello #{my_string}"
    
    hello_world_string
    => "Hello World!"