janl / mustache.js

Minimal templating with {{mustaches}} in JavaScript

Home Page:https://mustache.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bracket notation support for property access ?

NPavie opened this issue · comments

Hi !

I have a small issue when testing a template where some of my properties are having spaces in there name.

When looking at the code, I saw in comment that the context lookup function in the code does not handle bracket notation.
Is there a plan to also support bracket notations when viewing lookup ?

I managed to bypass this issue by first using a section for my current case but I see some cases where I would have many of them and that would make my template less readable.

I also managed on my side to modify this block on my installed version of mustache.js to handle "simple" bracket notation (and array access) but I'm not sure about my code retrocompatibility.

Here is the code I have used instead for the mentioned block: (to be improved)

if (name.indexOf('.') > 0 || name.indexOf('[') > 0) {
  intermediateValue = context.view;
  names = name.split(/\[|\./).map(
    (newName) =>  newName.replaceAll(/\]|\"|\'/g,'').trim()
  );

  index = 0;
  /**
   * Using both dot and bracket notion path in `name`, we descend 
   * through the nested objects.
   *
   * To be certain that the lookup has been successful, we have to
   * check if the last object in the path actually has the property
   * or the indexed value (if it is an array) we are looking for.
   * We store the result in `lookupHit`.
   *
   * This is specially necessary for when the value has been set to
   * `undefined` and we want to avoid looking up parent contexts.
   *
   * In the case where dot notation is used, we consider the lookup
   * to be successful even if the last "object" in the path is
   * not actually an object but a primitive (e.g., a string, or an
   * integer), because it is sometimes useful to access a property
   * of an autoboxed primitive, such as the length of a string.
   **/
  while (intermediateValue != null && index < names.length) {
    if (index === names.length - 1)
      lookupHit = (
        hasProperty(
          intermediateValue,
          names[index]
        ) || primitiveHasOwnProperty(
          intermediateValue,
          names[index]
        ) || (
          Array.isArray(intermediateValue) && 
          /^\d+$/.test(names[index]) && 
          intermediateValue.length > +names[index]
        )
      );

    intermediateValue = intermediateValue[
      Array.isArray(intermediateValue) ? 
        +names[index++] :
        names[index++]
    ];
  }
} else {
...
}

Is there a plan to also support bracket notations when viewing lookup ?

Afraid not. Although it's within reach to do so, mustache.js is meant to be a JavaScript implementation of the mustache spec first and foremost.

You are ofcourse free to fork and do whatever you want if it helps your use case 👍🏻