Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer: How to loop and render HTML to screen

Tags:

polymer

I am working on a widget that pulls third party information from a database using json. Once the information has been collected, I plan to loop through the information and create the required HTML code and insert this into the template via a {{variable}}

Now I am getting an unexpected result. When I do this, the html is being displayed as text.

Here is some sudo code of the issue:

       <polymer-element name="loop-element">
            <template>
                  {{customerList}}
            </template>
            <script>
                Polymer('loop-element', {
                   ready: function() {
                       this.loadCustomerList();
                   }
                   customerList:"Loading customer list...",

                   loadCustomerList: function() {
                       CustomerNameArray[] = //Get the array from jSon file
                       i = 0;
                       do {
                           this.customerList = "<div>" + customerNameArray[i] + "</div>";
                       } while (customerNameArray[i]);
                   }

                });

            </script>
        </polymer-element>

Essentially the DIV's are not being rendered, instead they are being printed to the screen as text:

"<div>Name 1</div>" "<div>Name 2</div>" ... n

Instead of:

Name 1
Name 2
Name n...

You can see a JSBin example here: http://jsbin.com/tituzibu/1/edit

Can anyone recommend how to go about outputting a list to the template?

like image 570
HappyCoder Avatar asked Apr 09 '14 21:04

HappyCoder


2 Answers

Polymer v.1.0

/* relative path to polymer.html*/
<link rel="import" href="../bower_components/polymer/polymer.html">

<dom-module id="employee-list">
    <style>
        /* CSS rules for your element */
    </style>
    <template>
        <div> Employee list: </div>
        <template is="dom-repeat" items="{{employees}}">
            <div>First name: <span>{{item.first}}</span></div>
            <div>Last name: <span>{{item.last}}</span></div>
        </template>
    </template>
</dom-module>

<script>
    Polymer({
        is: 'employee-list',
        ready: function() {
            this.employees = [
                {first: 'Bob', last: 'Smith'},
                {first: 'Sally', last: 'Johnson'}
            ];
        }
    });
</script>

doc

like image 190
Sajin M Aboobakkar Avatar answered Sep 17 '22 13:09

Sajin M Aboobakkar


You should use Polymer's DOM-based data-binding features rather than creating the markup yourself.

<template repeat="{{customer, i in customers}}">
  <div>{{i}}, {{customer.name}}</div>
</template>

http://www.polymer-project.org/docs/polymer/databinding.html#an-example

like image 25
ebidel Avatar answered Sep 18 '22 13:09

ebidel