简体   繁体   中英

How to use Jinja2 template in eel python?

I want to create an desktop application in python, so I started using the eel library to easily design a nice looking GUI application using html, css & javascript.

I have the following code in which I have imported the eel module and started the application with web/templates/index.html file to display as the main page & I have created a variable name which I want to use in the template and display it's value:

main.py

import eel
import pyautogui

name = 'Ajay'

eel.init('web')
eel.start(
    'templates/index.html', 
    size=pyautogui.size(), 
    jinja_templates='web/templates'
)

project's directory tree

FirstProj
  - main.py
  - web/
      - templates/
          - index.html

index.html

<html>
   <head>
       <script type="text/javascript" src="/eel.js"></script>
   </head>
   <body>
       <h1> Hello {{name}}! </h1>
   </body>
</html>

I found out that using the jinja2_template method of eel.btl I can fill the values context values into the template. but how to render it? I tried the following but it didn't work:

import eel, pyautogui

context = { 'name': 'Ajay' }
temp = eel.btl.jinja2_template('web/templates/index.html', context)

eel.init()
eel.start(temp, size=pyautogui.size(), jinja_templates='web/templates')

It showed me the following error page:

错误

Any help will be appreciated. Thanks in advance!

I found the solution installing eel[jinja2] after that it needs to have a structure folder like

.
├── app.py
└── web
    ├── css
    │   ├── bulma.min.css
    │   └── main.css
    ├── js
    │   └── main.js
    └── templates
        ├── base.html
        └── index.html

for start in app.py

eel.start(
    'templates/index.html',
    jinja_templates='templates'
)

in the base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Eel example</title>

    <link rel="stylesheet" href="../css/main.css" />
    <link rel="stylesheet" href="../css/bulma.min.css" />
    <script type="text/javascript" src="/eel.js"></script>
</head>
<body>
  {% block content %}
  {% endblock %}
</body>
<script src="../js/main.js"></script>
</html>

and in index.html

{% extends "base.html" %}

{% block content %}
<h1 class="title has-text-centered">Hello world!</h1>
{% endblock %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM