How can I structure my MustacheJS template to add dynamic classes based on the values from a JSON file?

Posted by JGallardo on Stack Overflow See other posts from Stack Overflow or by JGallardo
Published on 2013-07-02T22:42:48Z Indexed on 2013/07/02 23:05 UTC
Read the original article Hit count: 303

Filed under:
|
|
|
|

OBJECTIVE
To build an app that allows the user to search for locations.

CURRENT STATE
At the moment the locations listed are few, so they are just all presented when landing on the "dealers" page.

BACKGROUND
Previously there were only about 50 showrooms carrying a product we sell, so a static HTML page was fine.

example of code

And displays as

displays as

But the page size grew to about 1500 lines of code after doing this. We have gotten more and need a scalable solution so that we can add many more dealers fast. In other projects, I have previously used MustacheJS and to load in values from a JSON file. I know the ideally this will be an AJAX application. Perhaps I might be better off with database here?

Below is what I have in mind so far, and it "works" up to a certain point, but seems not to be anywhere near the most sustainable solution that can be efficiently scaled.

HTML

<a id="{{state}}"></a>
      <div>
        <h4>{{dealer}} : {{city}}, {{state}} {{l_type}}</h4>
        <div class="{{icon_class}}">
          <ul>
            <li><i class="icon-map-marker"></i></li>
            <li><i class="icon-phone"></i></li>
            <li><i class="icon-print"></i></li>
          </ul>
        </div>  

        <div class="listingInfo">
          <p>{{street}} <br>{{suite}}<br>
            {{city}}, {{state}} {{zip}}<br>
            Phone: {{phone}}<br>
            {{toll_free}}<br>
            {{fax}}
          </p>
        </div>
      </div>
<hr>  

JSON

{ "dealers" : [
  { 
    "dealer":"Benco Dental",
    "City":"Denver",
    "state":"CO",
    "zip":"80112",
    "l_type":"Showroom",
    "icon_class":"listingIcons_3la",
    "phone":"(303) 790-1421",
    "toll_free":null,
    "fax":"(303) 790-1421"
    },
    {
    "dealer":"Burkhardt Dental Supply",
    "City":"Portland",
    "state":"OR",
    "zip":"97220",
    "l_type":"Showroom",
    "icon_class":"listingIcons",
    "phone":" (503) 252-9777",
    "toll_free":"(800) 367-3030",
    "fax":"(866) 408-3488"  
  }
]}


CHALLENGES

  • The CSS class wrapping the ul will vary based on how many fields there are. In this case there are 3, so the class is "listingIcons_3la"

  • The "toll free" number section should only show up if in fact, there is a toll free number.

  • the fax number should only show up if there is a value for a fax number.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html