Escaping line-return / end of line in ERB templates

I need to be able to format non-printable logical lines in ERB without affecting the final text output of the template. At the moment, I do not think that ERB supports such acceleration.

This is my first major Ruby project. I am writing a code generator. My templates will contain a significant amount of conventions and enumerations. To make the template readable and supported, I need to be able to format the logical code and comments without distorting the final output.

eg. Suppose I want this output:

Starting erbOutput 1 2 3 4 Ending erbOutput 

I naively wrote a template something like this:

 require 'erb' h=<<H Starting erbOutput <%# comment %> <%5.times do |e|%> <%=e.to_s %> <%end %> <%# comment %> Ending erbOutput H s=ERB.new(h).result puts s 

... but it creates

 Starting erbOutput 0 1 2 3 4 Ending erbOutput 

Direct fingerprint:

 "Starting erbOutput\n\n\n0\n\n1\n\n2\n\n3\n\n4\n\n\nEnding erbOutput\n" 

... makes it clear that linear returns of logical and line comments are included in ERB output.

I can create the desired result by sorting the template into this awkward form:

 h=<<H Starting erbOutput<%# comment %> <%5.times do |e|%><%=e.to_s %> <%end %><%# comment %>Ending erbOutput H 

... but I don’t think I can debug and maintain templates without more readable formatting. Some of my conventions and listings have three levels of depth, and I comment very much. Cramming everything on one or two lines makes the pattern completely unreadable.

Is there any way to escape or in some other way suppress the output of the comment logical line string in ERB? Does one of the other public Ruby template modules support this better?

In case that matters, I work on MacRuby 0.10 (implements Ruby 1.9.2) on MacOS 10.6.7.

+6
source share
4 answers

As Rom1 and Kyle suggest, you can pass parameters to ERB.new , but then you won't get line breaks wherever you want.

 require 'erb' h=<<H Starting erbOutput <%# comment %> <%5.times do |e|%> <%=e.to_s %> <%end %> <%# comment %> Ending erbOutput H s=ERB.new(h, nil, '<>').result puts s 

gives you

 Starting erbOutput 01234Ending erbOutput 

So you need to explicitly insert extra lines

 require 'erb' h=<<H Starting erbOutput <%# comment %> <%5.times do |e|%> <%=e.to_s %> <%end %> <%# comment %> Ending erbOutput H s=ERB.new(h, nil, '<>').result puts s 

This will give:

 Starting erbOutput 0 1 2 3 4 Ending erbOutput 
+3
source

Minus sign?

 <%# comment -%> <% 5.times do |e| -%> <%= e.to_s -%> <% end -%> <%# comment -%> 
+4
source

You can change the settings for erb. Here is a quick tutorial: http://www.ruby-forum.com/topic/55298

+1
source

erb -T 1 foo.erb

I assume the library has an equivalent option (possibly trim_mode ctor param).

0
source

Source: https://habr.com/ru/post/887868/


All Articles