baryshev / ect

Fastest JavaScript template engine with embedded CoffeeScript syntax

Home Page:http://ectjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How Include helper functions from other ect file.

harish2704 opened this issue · 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?

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>

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

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