Back to the index of articles and examples

YQLSubstitute using the YQLQuery component

We are using the YQLQuery module to fill in a list with the restults of a YQL query based on a template. This is a YUI3 version of this YUI2 example.

After the initial call to YUI().use() to load the required components we define the YQLSubstitute function which takes:

  1. A reference to the container where the results will be stored
  2. The YQL query to be executed
  3. The template to use on the results

Once the YQLQuery instance is created, you can either provide a callback function or listen to the completion events. Here we have used the callback. The single r argument can either contain an error property with the error message, which we show in the container or the actual results which will be in a property under r.query.results. Since by this time we know there are not other worthy members of r, we resolve the results into r itself.

Unfortunately, YQL produces the results in various ways.

Usually, we would expect a more predictable result, always an array with 0, 1 or more results, but YQL is not consistent in this. What we do is start a loop over the keys in the r object and pick the first property listed and then run another loop over whatever that property contains, which may or may not be an array, so we first make sure it is one using the static Y.Array and then Y.Array.each to loop through it.

The YUI2 version of YQLSubstitute, which uses YQLDataSource, has this solved by YQLDataSource.

For each item we pile up into output the results of substituting each record into the template and, when done, set the contents of the container with the results

In contrast to the YUI2 version, this one does not support nested fields nor parsing the field values.