ect icon indicating copy to clipboard operation
ect copied to clipboard

How Include helper functions from other ect file.

Open harish2704 opened this issue 11 years ago • 3 comments

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?

harish2704 avatar Mar 05 '14 16:03 harish2704

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>

baryshev avatar Mar 08 '14 08:03 baryshev

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 %>

harish2704 avatar Mar 09 '14 03:03 harish2704

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} %>

hytromo avatar Feb 01 '17 23:02 hytromo