Coded something up in Couch in an interesting way? Have a snippet or shortcode to share? Post it here for the community to benefit.
3 posts Page 1 of 1
Hello friends,

Please let me know of any way to convert a basic table-like presentation to <ul><li> from the sample:
Code: Select all
a | 1
a | 2
b | 10
b | 20
b | 30
c | 100

to
Code: Select all
<ul> 
      <li>a
            <ul>
                  <li>1</li>
                  <li>2</li>
            </ul>
      </li>
      <li>b</li>
      <li>c</li>
</ul>


Is it difficult with Couch tags? Maybe some simple trick?
I have a cms:query, which gives me data in this format, like FOLDER-ID - PAGE-TITLE,
So it can be
folder1 - page1
folder1 - page2
folder2 - page3
folder2 - page4

So, I need to create an hierarchical list with only 2 levels. Thanks.
With introduction of multi-value variables (arrays) we have a good way to rewrite the code and make things simpler.

I'll take a sample real-life use case with following query:

Code: Select all
<cms:capture into='sql'>SELECT cf.id, cf.name, cf.template_id, cf.label FROM couch_fields cf</cms:capture>

It lists editable fields from 'couch_fields' table in database.
Regular output with table has 4 columns: template_id, field_name, field_id, field_label

Code: Select all
<h2>TABLE</h2>
<table>
<cms:query sql=sql limit='10000'>
    <tr><td><cms:show template_id /></td><td><cms:show name /></td><td><cms:show id /></td><td><cms:show label /></td></tr>
</cms:query>
</table>

It starts and goes on like this:

2017-09-09-045431.png
2017-09-09-045431.png (24.93 KiB) Viewed 4218 times


Now a working code for JSON output, with hierarchy:

Code: Select all
<cms:set cf = '[]' is_json='1' scope='global' />
<cms:query sql=sql limit='10000'>
    <cms:if "<cms:not "<cms:arr_key_exists "<cms:show template_id />" in=cf />" />" >
        <cms:put var="cf.<cms:show template_id />" value='[]' is_json='1' scope='global' />
    </cms:if>
    <cms:capture into="cf.<cms:show template_id />.<cms:show name />" is_json='1' >
        { "id" : "<cms:show id />", "label" : "<cms:show label />" }
    </cms:capture>
</cms:query>
<cms:show cf as_json='1' />

Structure is seen in this output (cut out to sample)

Code: Select all
{
   "4":{
      "extended_user_id":{
         "id":"5",
         "label":"Extended-User ID"
      },
      "extended_user_email":{
         "id":"6",
         "label":"Extended-User Email"
      }
   },
   "8":{
      "address":{
         "id":"18",
         "label":"Office Street Address"
      },
      "tel_1":{
         "id":"22",
         "label":"Tel 1"
      }
   }
}


This required some hard time to figure out, will be glad if it helps someone.

Now, if we take the same task from the first post, then converting JSON to <ul><li> becomes very easy, manageable and with multi-level depth.
This is v useful

Is there a way to sort JSON output in any order?
3 posts Page 1 of 1