Daniel Reiner
Daniel Reiner

Reputation: 137

How to escape erb tags for a template in rails view file?

I try to use clndr.js in my Rails project and therefor use an unslider-template. This template contains "<% %>" <%= %>" tags and throw errors because the template variables are undefind.

Any ideas on how I can prevent rails to execure the "<% %>"-tags?

This is the code of my view:

<div id="mini-clndr"></div>


<script id="calendar-template" type="text/template">
  <div class="controls">
    <div class="clndr-previous-button">&lsaquo;</div><div class="month"><%%= month %></div><div class="clndr-next-button">&rsaquo;</div>
  </div>

  <div class="days-container">
    <div class="days">
      <div class="headers">
        <% _.each(daysOfTheWeek, function(day) { %><div class="day-header"><%%= day %></div><% }); %>
      </div>
      <% _.each(days, function(day) { %><div class="<%= day.classes %>" id="<%= day.id %>"><%%= day.day %></div><% }); %>
    </div>
  </div>
</script>




  <% content_for(:scripts) do %>
<script type="text/javascript">

      var currentMonth = moment().format('YYYY-MM');
  var nextMonth    = moment().add('month', 1).format('YYYY-MM');
  var events = [
    { date: currentMonth + '-' + '10', title: 'Persian Kitten Auction', location: 'Center for Beautiful Cats' },
    { date: currentMonth + '-' + '19', title: 'Cat Frisbee', location: 'Jefferson Park' },
    { date: currentMonth + '-' + '23', title: 'Kitten Demonstration', location: 'Center for Beautiful Cats' },
    { date: nextMonth + '-' + '07',    title: 'Small Cat Photo Session', location: 'Center for Cat Photography' }
  ];

$('#mini-clndr').clndr({
    template: $('#calendar-template').html(),
    events: events,
    clickEvents: {
      click: function(target) {
        if(target.events.length) {
          var daysContainer = $('#mini-clndr').find('.days-container');
          daysContainer.toggleClass('show-events', true);
          $('#mini-clndr').find('.x-button').click( function() {
            daysContainer.toggleClass('show-events', false);
          });
        }
      }
    },
    adjacentDaysChangeMonth: true
  });

</script>
<% end %>

Upvotes: 1

Views: 840

Answers (2)

Bob Nadler
Bob Nadler

Reputation: 1277

Use <%%= your-ruby-code %>. Notice the double %% at the beginning, but not at the end of the tag.

Upvotes: 5

raj_on_rails
raj_on_rails

Reputation: 144

One of the best method is converting erb to haml. Add gem 'haml' in Gemfile and bundle install. Add your erb code in http://htmltohaml.com/ and copy the converted haml code in your file and rename it as yourfilename.html.haml.

it works..

Upvotes: 0

Related Questions