baryshev / ect

Fastest JavaScript template engine with embedded CoffeeScript syntax
http://ectjs.com
MIT License
626 stars 69 forks source link

How Include helper functions from other ect file. #63

Open harish2704 opened 10 years ago

harish2704 commented 10 years ago

Hi, Is there any way to include a collection of helpers from a 'helper only' ect file? using normal 'include' tags does not exports the helpers defined in the template to current context. Is there any way to do this?

baryshev commented 10 years ago

You can use @ prefix to export helpers from included file.

Example:

helpers.ect

<% @helloHelper = (name) -> %>
    Hello, <%- name %>!
<% end %>

<% @strongHelper = (string) -> %>
    <strong><%- string %></strong>
<% end %>

page.ect

<% include 'helpers' %>

<div>
<%- @helloHelper 'John Smith' %>
</div>
<div>
<%- @strongHelper 'strong string' %>
</div>
harish2704 commented 10 years ago

Thank you . so I understand that calling 'include' tag without any second argument passes 'this' object to calling template as its 'this' . It will be helpful if this info is included in documentation.

Till now what i was doing is

// page.ect
<% helpers = {} %>
<% include 'helpers' , helpers %>
//helpers.ect
<% @helperes.somHelper = (arg1) -> processArg arg1 %>
hytromo commented 7 years ago

I had a problem with using helpers inside an included ect file while I have passed parameters to it at the same time.

main.ect includes partial.ect with parameters {h: 0, m:10}. partial.ect includes helpers.ect but this inside partial.ect is just an object containing {h:0, m:10} and not the helper functions defined inside helpers.ect.

The workaround that worked for me was to pass this along with the other variables. Then the functions seem to be attached just fine. So the working code would be something like

// main.ect:
<% include 'partial', {this: this, h: 0, m: 10} %>