Project

General

Profile

Feature #15538

Updated by kke (Kimmo Lehto) almost 6 years ago

In `Erb`, would it be possible to add a new tag trim mode that would indent the following content to match the depth of the tag? The tag could for example be `<%~` (to resemble the `<<~EOS` squiggy heredoc). `<%|` and it would be enabled using `Erb.new(template, trim_mode: '|')` 

 ## Reason 

 Something like this would be easy to follow: 

 ``` ruby 
 1 
 <%- [2, 3, 4].each do |num| -%> 
   <%- unless num == 3 -%> 
     <%= num %> 
   <%- end -%> 
 <%- end -%> 
 5 
 ``` 

 But unfortunately it will render with "extra" indentation: 

 ``` 
 1 
     2 
     4 
 5 
 ``` 

 Currently, to avoid this, you have to write your template using either no indentation: 

 ``` 
 1 
 <%- [2, 3, 4].each do |num| -%> 
 <%- unless num == 3 -%> 
 <%= num %> 
 <%- end -%> 
 <%- end -%> 
 5 
 ``` 

 Or a weird jumpy indentation: 

 ``` 
 1 
 <%- [2, 3, 4].each do |num| -%> 
   <%- unless num == 3 -%> 
 <%= num %> 
   <%- end -%> 
 <%- end -%> 
 5 
 ``` 

 With the `<%~` `|`    trim mode it could be written as: 

 ```ruby 
 1 
 <%~ <%|- [2, 3, 4].each do |num| -%> 
   <%- unless num == 3 -%> 
     <%= num %> 
   <%- end -%> 
 <%~ <%|- end -%> 
 5 
 ``` 

 And it would output as desired without the "extra" indentation: 

 ``` 
 1 
 2 
 4 
 5 
 ``` 

 Another example: 

 ``` 
 <%= "abcd" %> <%~ [1.2.3].each do |num| -%> 
                 <%= num %> 
               <%~ end -%> 
 ``` 

 would produce: 

 ``` 
 abcd 1 
      2 
      3 
  ``` 


 ## Using with `=` 

 It would also be handy if the `~` `|` could be used in `<%=` statements, with `<%=`, perhaps as `<%~=`. This `<%|=`, this would be excellent for example when templating YAML's: 

 ```yaml 
 <%- bars bar_content = %w(abc def)" "- abc\n- " -def" -%> 
 foo: 
   bar:  
     <%~= bars.map { |bar| "- #{bar}\n" } %> <%|= bar_content |%> 
 ``` 

 Which would reindent the statement outcome to produce something like: 

 ```yaml 
 foo: 
   bar: 
     - abc 
     - def 
 ``` 

 This would require these new tags: 

 1. `<%~` `<%|` begin a code capturing a block and begin or end reindentation mode. content produced inside the block which will be reindented to the depth column of the `<` character in `<%~`. If 
 2. `|%>` end the indentation mode was already active due to a previous `<%~`, it ends the indentation mode. capturing block 
 2. `<%~=` 3. `<%|=` like regular `<%=` but multiline strings will be reindented to the column of the `<` character 

 Optionally versions of the block tags with whitespace trim control: 

 4. `<%-|` like `<%|` but if block outputs nothing, remove leading whitespace 
 5. `|-%>`like `|%>` but remove trailing whitespace and linefeed from the line this tag appears on 

Back