Search code examples
pythongoogle-app-enginepolymerjinja2template-engine

Pass values from backend to frontend in polymer


I am building a web app using Google App Engine and Polymer.

Before using polymer I used to pass my values to the frontend using jinja2 templating:

def render_str(self, template, **params):
    t = JINJA_ENV.get_template(template)
    return t.render(params)

def render(self, template, **kw):
    self.write(self.render_str(template, **kw)))

-

{% for note in notes %}
<div class="note">
    <div>{{note.title}}</div>
    <div>{{note.created}}</div>
</div>
{% endfor %}

This works fine for the main page but all imported polymer files are out of the scope of these passed values.

How can I pass values from my backend to my polymer forms? Is there a way to get my imported polymer files in the same scope as my main page or is there an alternate template engine I could use? I saw that polymer has its own templating and data binding but I could not find a way to fill these with values from my backend.


Solution

  • Data binding is pretty simple in Polymer. Use the Polymer Expressions, e.g.

    var testString = "Hello"
    
    <div id="test" class="test">{{testString}}</div>
    
    document.getElementById("test").testString = "Whats up?";
    

    To pass a value from your main page to a component, you can either use the attribution model, e.g.

    <my-polymer-component id="test" mydata="Hello" />
    
    <polymer-element attributes="mydata ...">
    

    or just assign it to the Polymer element itself:

    document.getElementById("test").mydata = "Whats up";
    

    The variables are auto populated into the Polymer element. Reading from it would be the same - as long they are exposed on the element itself or even defined in the actual Polymer object:

    Polymer('my-polymer-component', {
     mydata: 'foo',
    
     ready: function() { ... }
    });