XaminProject / handlebars.php

Handlebars processor for php
331 stars 132 forks source link

How to extend Context in custom helper? #148

Closed jcubic closed 8 years ago

jcubic commented 8 years ago

I wan to create custom helper sql:

<ul>
{{#sql SELECT * FROM users}}
   <li>{{username}}<br/>
   <ul>
      {{#sql SELECT * from files where user.id = [id]}}
          <li>{{filename}}</li>
      {{/sql}}
    </ul></li>
{{/sql}}
</ul>

how can I use Context in custom helper to make it work? Also if I'm in helper and call $context->get('id'); will it return the id from sql higher in hierarchy? Do I need to modify Helpers.php to add this helper or is there a way to do it outside of the library in user code?

everplays commented 8 years ago

First of all, bundling the logic and markup is not a good idea. If that's what you want, embedding html and php in one file would be much better option. Specially because of its performance compared to what you get from this library.

However, if you in really want to do this, have a look at ChildContext. Basically, you need to extend it and provide the data that you want to it. If a variable didn't exist in your own implementation, you fall back to parent context.

everplays commented 8 years ago

Also you might find https://github.com/XaminProject/handlebars.php/pull/132#issuecomment-158027024 interesting. That's another way to approach this.

jcubic commented 8 years ago

You already have logic in handlerbars like #each and #if, so I don't think there is the reason why not to add just one more logic helper.

JustBlackBird commented 8 years ago

#each and #if aren't the same as #sql. Also, running database queries from templates is a very-very bad practice in any template engine community. Even if you can do so you definitely should not.