-1

I'm looking for a way to pass a value to a list enumerable, so I could produce a set of list items for a <ul>. The value should be displayed by the item that allows it.

  • new
  • favorites (15)           <-- 15 being the value I want displayed.
  • archived
  • deleted

The following does not work as is, but should help illustrate the goal to achieve.

HAML

%ul
  =list_of t('.menu', favorites_count: 15) do |item|
    #{item}

YAML

menu:
  - new
  - favorites ('%{favorites_count}')
  - archived
  - deleted

Note: initially I had my YAML include the <li> tags in a dictionary form, inside strings, one of which includes the count value. But I find it a bit clumsy to mix HTML and YAML, like so:

menu:
  first_item: <li>new</li>
  second_item: <li>favorites %{favorites_count}</li>
  third_item: <li>archived</li>
  fourth_item: <li>deleted</li>

Hence looking for a cleaner option, that will only render tags on the HAML side and not litter them in YAML.

Rui Nunes
  • 798
  • 1
  • 8
  • 15

1 Answers1

1

I18n.t uses interpolation syntax very similar to sprintf's, which you can use to your advantage:

%ul
  = list_of t(".item") do |item|
    = sprintf(item, favorites_count: 15)

I'm not entirely sure that's the right Haml syntax, but you get the idea.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • Good stuff, managed to shorten it a bit: = "#{item}" % { favorites_count: 15 } – Rui Nunes Jun 10 '16 at 08:02
  • 1
    Don't do `"#{item}"`. `#{...}` is for string interpolation, but you're not interpolating anything here. If you know `item` is a string, just use `item`. If you're not sure it's a string, use `item.to_s`. In other words, do `= item % ...` or `= item.to_s % ...`. `"#{...}"` is always needless. – Jordan Running Jun 10 '16 at 12:44