Cherrypy – Pass List From Python to HTML via Jinja

Cherrypy – Pass List From Python to HTML via Jinja



Rating : 5/5 (2)




Introduction

In the previous tutorial we looked at HelloWorld Cherrypy application. We also saw how to install Cherrypy via pip or easy-install. Cherrypy is a python web framework that's quite minimalistic and clean. Its fully object oriented and easy to work with and setup.
In this tutorial we see how to pass list of data from python code to html user interface and show in a material list. We will use jinja templating language. We pass both list and strings and loop through them in html and show them.

Cherrypy Installation

  • To Install Cherrypy use any of the following commands:
easy_install cherrypy
pip install cherrypy

You can also get it from github:

git clone https://github.com/cherrypy/cherrypy
cd cherrypy
python setup.py install

For more information on cherrypy installation please here is detailed guide.

Jinja Installation

  • Jinja like cherrypy can installed using easy-install or pip.
easy_install Jinja2
pip install Jinja2

Tools Used

Language : Python 3.5, HTML
Platform : Backend and Fronted Web
IDE : PyCharm
Topics : Object Oriented Python, Cherrypy install,Cherrypy hello world, Cherrypy Routing

Questions this Project answers.

  • Cherrypy pass list from python code to html.
  • Cherrypy list example.
  • How to use Cherrypy with jinja.
  • How to pass list to html via jinja.
  • CherryPy web development example
  • Python web development.

Libraries Used

These are the third party CSS and JS used in this project.

Screenshot

  • Here's the screenshot of the project.
    CherryPy Hello World

Project Structure

  • Here's the structure of the project.

CherryPy Pass List Project Structure

Source Code

Lets have a look at the source code.

Index.pyindex.htmlVideo/DemoDownload
  • Our Main class.
  • We import jinja once we have it installed.
  • We reference our target html file using jinja and use it as the template.
  • We'll create a list with items and pass it to our template.
  • We'll call template.render() method passing in the data we want to pass to the template.In this case we pass strings as well as list.
import os
import cherrypy
from jinja2 import Environment, FileSystemLoader
# GET CURRENT DIRECTORY
CUR_DIR = os.path.dirname(os.path.abspath(__file__))
env=Environment(loader=FileSystemLoader(CUR_DIR),
trim_blocks=True)
# OUR CONTROLLER
class Index(object):
    # INDEX ACTION MAPPED TO HOMEPAGE
    @cherrypy.expose()
    def index(self):
        template = env.get_template('index.html')
        # RENDER TEMPLATE PASSING IN DATA
        return template.render(title='Amazing Universe', description='Our universe is quite amazing',list_header="Galaxies!", galaxies=self.get_galaxies(),site_title="Camposha.info")
    # HELPER FUNCTION TO RETURN GALAXIES LIST
    def get_galaxies(self):
        galaxies=["Messier 81","StarBurst","Black Eye","Cosmos Redshift","Sombrero","Hoags Object","Andromeda","Centarus A","Whirlpool","Canis Major Overdensity"]
        return galaxies
if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.staticdir.root': os.path.abspath(os.getcwd())
        },
        '/static': {
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './public'
        }
    }
    # RUN
    cherrypy.quickstart(Index(), '/', conf)

 

  • Our index.html file.
  • We'll pass it data from code via jinja.
  • We give it material design theme using materializecss.
  • We'll use jinja expressions with double curly braces passing in our template variables.We also loop through our galaxies list.
 <!DOCTYPE html5>
<html lang="en">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
  <title>Camposha.info</title>
  <!-- CSS  -->
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link href="static/css/materialize.min.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="static/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
</head>
<body>
<nav class="green lighten-1" role="navigation">
    <div class="nav-wrapper container"><a id="logo-container" href="#" class="brand-logo">{{site_title}}</a>
      <ul class="right hide-on-med-and-down">
     <li><a href="/">Home</a></li></ul>
      <a href="#" data-activates="nav-mobile" class="button-collapse"><i class="material-icons">menu</i></a>
    </div>
  </nav>
<div class="container">
     <h1 class="header center orange-text">{{ title }}</h1>
   <h5 class="header center col s12 light">{{description}}</h5>
      <p>Here are our galaxies</p>
      <ul class="collection with-header">
        <li class="collection-header"><h4>{{list_header}}</h4></li>
        {% for galaxy in galaxies %}
        <li class="collection-item"><a href="#">{{galaxy}}</a></li>
        {% endfor %}
      </ul>
<br>
  <br>
</div>
  <footer class="page-footer light-green">
    <div class="container">
      <div class="row">
        <div class="col l6 s12">
          <h5 class="white-text">Company Bio</h5>
          <p class="grey-text text-lighten-4">Galactic News brings the latest planetary, stellar and galactic news.</p>
        </div>
        <div class="col l3 s12">
          <h5 class="white-text">Reach Us</h5>
          <ul>
            <li><a class="white-text" href="#!">About Us</a></li>
            <li><a class="white-text" href="#!">Contact Us</a></li>
            <li><a class="white-text" href="#!">News</a></li>
            <li><a class="white-text" href="#!">Terms</a></li>
          </ul>
        </div>
        <div class="col l3 s12">
          <h5 class="white-text">Connect</h5>
          <ul>
            <li><a class="white-text" href="#!">Facebook</a></li>
            <li><a class="white-text" href="#!">Twitter</a></li>
            <li><a class="white-text" href="#!">Linkedn</a></li>
            <li><a class="white-text" href="#!">Google Plus</a></li>
          </ul>
        </div>
      </div>
    </div>
    <div class="footer-copyright">
      <div class="container">
      Made by <a class="orange-text text-lighten-3" href="http://camposha.info">Camposha</a>
      </div>
    </div>
  </footer>
  </body>
</html>

 

  • For detailed explanation as well as demo please check Video version of this tutorial below.

Python Web S1E2 : CherryPy - Pass List Via Jinja

  • You can Download the full Project below:
Download

How to Download and Run.

  1. Download the project above.
  2. You'll get a zipped file,extract it.
  3. Extract and import into your IDE and run.

More

  • Visit our channel for more examples like these.
  • Lets share tips and ideas in our Facebook Page.

Oclemy,Cheers.



Rating :

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    11 − 1 =

    COMMENTS