croxton / Stash

Stash allows you to stash text and snippets of code for reuse throughout your templates.
GNU General Public License v3.0
197 stars 20 forks source link

FR: "output formatting" concept for get/get_list #97

Open timkelty opened 10 years ago

timkelty commented 10 years ago

Example:

{exp:stash:set_list name="companies"}
  {stash:company}Fusionary{/stash:company}
  {stash:city}Grand Rapids{/stash:city}
  {stash:company}Hallmark Design{/stash:company}
  {stash:city}Brighton{/stash:city}
{/exp:stash:set_list}

{exp:stash:get_list
  name="companies"
  output_format="json"
}

Would render:

[
  {
    "company": "Fusionary",
    "city": "Grand Rapids"
  },
  {
    "company": "Hallmark Design",
    "city": "Brighton"
  }
]

Example 2 (using same set as #1):

<div class="{exp:stash:get_list name="companies" output_format="class_attribute"}"></div>

Would render:

<div class="fusionary grand_rapids hallmark_design brighton"></div>

Example 3:

{exp:stash:set_list name="attrs"}
  {stash:class}class1 otherClass{/stash:class}
  {stash:id}my-id{/stash:id}
  {stash:data-foo}myDataValue{/stash:data-foo}
{/exp:stash:set_list}

<div {exp:stash:get_list name="attrs" output_format="html_attributes"}></div>

Would render:

<div class="class1 otherClass" id="my-id" data-foo="myDataValue"></div>

I for one, would get endless use out of this. Much of the stash wrangling I do is for output like this.

What would be really cool, is if you modularized each "output format" or provided a hook, so that others could make output format extensions themselves!

croxton commented 10 years ago

I think this is a great idea, and I need this too.

GDmac commented 10 years ago

i first just thought about quickly adding a snippet to rebuild_list(). e.g. if (tagparam('output_format')=='json') return json_encode($list);

then, actually, all you need is this in a quick plugin

    public function json() 
    {
        $this->EE = get_instance();

        // Pass on the parameters to stash :-)
        // name="listname" type="snippet" scope="site" 
        // match="#{segment_3}#" against="entry_id"
        $params = $this->EE->TMPL->tagparams;

        $list = Stash::rebuild_list($params);
        return json_encode($list, JSON_PRETTY_PRINT);
    }