Domanda

I know that the Jinja2 library allows me to pass datastore models from my python code to html and access this data from inside the html code as shown in this example . However Jinja2 isn't compatible with javascript and I want to access the data inside my Javascript code . What is the simplest templating library which allows to iterate over my datastore entities in Javascript ? I've heard about things like Mustache and Jquery , I think they look a bit too complicated. Is there anything simpler?

È stato utile?

Soluzione 4

It works. I had to serialize(convert) my datastore entities to json format, which Javascript understands well. I created a function which converts every instance of my datastore into a dictionnary then encapsulates all these instances into a list which is then converted to Json using json.dumps. When I pass this result to the Java script , I can then easily access my values as seen below.

import json
import webapp2
from google.appengine.ext import db

import jinja2

JINJA_ENVIRONMENT = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.autoescape'],
autoescape=True)

# serialize datastore model to JSON format
def serialize(model):

   allInstances = model.all() # fetching every instance of model
   itemsList = [] #initial empty list
   for p in allInstances:
      d = db.to_dict(p)
      itemsList.append(d)

return  json.dumps(itemsList)

class myModel(db.Model):
    v  = db.FloatProperty()
    c = db.FloatProperty()
    tdate = db.DateTimeProperty(auto_now_add=True)

class MainPage(webapp2.RequestHandler):
    def get(self):
       myModel(v=4.5, c=3.0).put()

       #creating template variables
       template_values = {
           'json_data':  serialize(myModel)
       }

       template = JINJA_ENVIRONMENT.get_template('index.html')
       self.response.write(template.render(template_values))

Inside my 'index.html' file, I have:

{% autoescape true %}
<!DOCTYPE html>
<html>
    <head>
        <title> webpage </title>
         <script type="text/javascript">

           // I retrieve my data here
           var results = "{{ json_data }}";
           for(var i = 0; i < db_results.length; i++) {

              document.write("myModel instance:" + i + results[i] + "<br>");

           } 
         </script>
    </head>

    <body>
    </body>
</html>
{% endautoescape %}

Altri suggerimenti

You should create a python controller which serves JSON formatted data, which any Javascript library (especially jQuery) can consume from. Then, setup the Jinja2 template to contain some Javascript which calls, loads and displays said data.

One more approach to consider: If the Python object is not dynamic, you may want to use json.dumps() to store it as a TextProperty, and simply JSON.parse(unescape(model_text)) on the JS side. Reduces the overhead, and memory hit which can be important when trying to stay within an F1 limit. For example, I run an instance that very easily runs inside an F1. There is one large dictionary object that we deliver. Were this object to exist as a Python dictionary inside the instance we would kill the instance due to the soft memory limit. Using the TextProperty approach we can pass this large dict to the client without any issues. (Note: we did have to momentarily boost our instance up to an F4 when initially creating this object -- something incredibly easy inside the Admin web page.) With more dynamic objects, answers above apply.

Jinja2 and Javascript play fine together. You need to arrange to have template expansion emit your Python data structures into a JS-friendly form.

https://sites.google.com/a/khanacademy.org/forge/technical/autoescape-in-jinja2-templates covers it fairly well. (Note the use of the escapejs filter.)

It has nothing to do with compatibility. Jinja is server side templating. You can use javascript for client side coding.

Using Jinja you can create HTML, which can be accessed by javascript like normal HTML. To send datastore entities to your client you can use Jinja to pass a Python list or use a json webservice.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top