Home > Net >  Display code block but also resolve variable within it
Display code block but also resolve variable within it

Time:06-09

Rails 7 / Ruby 3

I'm currently working on a site that requires code examples to be displayed on a page - I can get these to display utilising the extra % character trick, however, for some of the examples I need to have a variable within them that is resolved (e.g. like the users' own API key etc...).

Consider I have @variable = "Resolved Variable"

<%%= link_to @variable, variable_path %>

Outputs on the page explicitly as <%= link_to @variable, variable_path %>

But I really need the @variable to resolve and show on the page as:

<%= link_to "Resolved Variable", variable_path %>

I've tried all kinds of escaping the variable, but it seems that <%%= ensures that nothing following it can be resolved.

Any ideas?

CodePudding user response:

Any text you haven't html_encodeed will be displayed as plain text. My suggestion to you is to create a interpolated string that you could use to generate your intended result. For example:

output_text = "<%= link_to '#{@variable}', variable_path %>"

And, not sure if this is what you're looking for, but you can get a good UI by adding some Javascript library to format you code in the language in intend (in this case Ruby, it seems).

In case that's interesting to you, check the Prism lib, or check how to add it to your project here

I hope this helps. With kind regards, Rogerio

CodePudding user response:

<%% in ERB will simply output <%, no more, no less. In particular, it won't attempt to parse the code after <%% as Ruby. However, this doesn't mean that you can't have another <%= ... %> after <%%:

require 'erb'

template = <<-EOD
<%%= link_to <%= @variable.inspect %>, variable_path %>
EOD

@variable = "Resolved Variable"

puts ERB.new(template).result

The inspect method will add quotes around your string and also escape certain characters as needed.

Output:

<%= link_to "Resolved Variable", variable_path %>
  • Related