derbyjs / derby

MVC framework making it easy to write realtime, collaborative applications that run in both Node.js and browsers
http://derbyjs.com
4.72k stars 265 forks source link

Access more information from current section context in view helpers? #244

Closed farmerpaul closed 10 years ago

farmerpaul commented 11 years ago

I have written a view helper where I need to compare the current index of the currently looped section to the total number of elements in that section's array.

Basically I'm trying to recreate something similar to Dust's {@sep} helper: https://github.com/linkedin/dustjs/wiki/Dust-Tutorial#wiki-sep__Separator_helper_Available_in_Dust_V10_release

There doesn't seem to be a way from within the view helper function to access the array representing the current section. There is a way, from the helper, to find out the currently iterated index within that array, but not the former. I've had to work around this by designing the helper to accept the section array as an argument to the function; this is kind of redundant and is prone to error. It should happen automatically. Here's my function:

/**
 * Displays the given delimeter (or ", " if not provided) if currently iterated
 * element within the section is not the last element.
 * @param  {array}  section   Array of nearest section to check index against
 * @param  {string} delimiter Delimiter to use between items
 * @return {string}           Delimiter if not at the last element
 */
helpers.sep = function(section, delimiter) {
  delimiter = delimiter || ', ';
  if ( this.ctx.$index < section.length - 1 ) {
    return delimiter;
  }
  return "";
};

I would really like to be able to avoid having to pass this section argument. Helpers in other templating languages have convenient access to the array, but in my inspection of this (the only contextual object I know of from within the helper) I can't find that array referenced anywhere.

nateps commented 10 years ago

Master of Derby is now the rewritten 0.6 and I am removing previous issues pretty aggressively so that I can be more responsive to new issues.

Please re-open if this issue is still relevant in Derby 0.6.