Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String interpolation in HTML attributes in an ERB file

I have an attribute that looks like this:

 data-text = "I won ### by playing..."

Where ### should be a value that I have in @credits.

How am I supposed to place that there?

I am having the same trouble when trying to do:

data-url = <%= request.scheme %> + "//" + <%= request.port %> 

In this case I don't know how to place the "" that should be surrounding the whole scheme + port.

Thanks

like image 428
Hommer Smith Avatar asked Jun 21 '13 15:06

Hommer Smith


People also ask

What is HTML ERB file?

As @Chowlett mentioned before, erb stands for Embedded Ruby. When you define any file as ". html. erb" that means it's an HTML file with ruby code embedded in it and it is similar to ". rhtml" extension of rails file.

Can you interpolate in HTML?

Interpolation allows you to incorporate calculated strings into the text between HTML element tags and within attribute assignments. Template expressions are what you use to calculate those strings.

Does RuboCop format ERB?

Rubocop. Runs RuboCop on all ruby statements found in ERB templates. The RuboCop configuration that erb-lint uses can inherit from the configuration that the rest of your application uses.

How do ERB files work?

An ERB object works by building a chunk of Ruby code that will output the completed template when run. If safe_level is set to a non-nil value, ERB code will be run in a separate thread with $SAFE set to the provided level. eoutvar can be used to set the name of the variable ERB will build up its output in.


1 Answers

tag.attributes (Rails 7+)

Starting from Rails 7 there is a new convenient helper tag.attributes which allow generating HTML tag attributes like so:

<html>
<body>
  <tag
    <%= tag.attributes(
      data: {
        text: "I won #{@credits} by playing...",
        url: "#{request.scheme}//#{request.port}"
      }
    ) %>
  >
  </tag>
</body>
</html>

More examples can be found here.

Sources:

  • Pull Request.

  • Source Code.

like image 50
Marian13 Avatar answered Sep 19 '22 14:09

Marian13