A list of puns related to "Jinja"
Hey folks, I've created a project for using templated text files in your Gleam apps. It is a executable that parses a basic jinja-inspired template syntax and outputs Gleam modules that can be included in your application code to render the content of the template.
Thank you to michallepicki for all the help with set up testing & release workflows to generate pre-compiled binaries.
GitHub repo: https://github.com/michaeljones/gleam-templates/
Hi,
I am experiencing weird behavior and wondering if I am doing anything wrong. Would someone mind helping me out please?
My map.jinja:
{% set config = pillar['repository'] %}
{% for x,y in config.items() %}
{% for z in y %}
{% set config = z %}
{% endfor %}
{% endfor %}
My pillar:
repository:
unifi:
debian:
default:
url:
- deb http://www.ui.com/downloads/unifi/{{ grains.lsb_distrib_id | lower }} stable ubiquiti
key_server: http://download.proxmox.com/debian/proxmox-release-{{ grains['lsb_distrib_codename'] }}.gpg
key_id: 06E85760C0A52C50
ubuntu:
foo: bar
My template file:
{{ config|yaml(False) }}
{% for x,y in config.items() %}
{% for z in y %}
{{ z }}
{% endfor %}
{% endfor %}
So if I run the state the output file will look like:
unifi:
debian:
default:
key_id: 06E85760C0A52C50
url:
- deb http://www.ui.com/downloads/unifi/debian stable ubiquiti
key_server: http://download.proxmox.com/debian/proxmox-release-stretch.gpg
ubuntu:
foo: bar
debian
ubuntu
However I expected the first dict (unifi dict) to only contain the default key, and not the entire dict?
It should be overwritten in the map.jinja with config
in the for
loop, correct?
What am I doing wrong, or is this an actual bug?
Hi,
I've been working on a side project, and I would greatly appreciate feedback and ideas: hookglue.com
The idea is quite simple: You shouldn't need to deploy a server or microservice when all you want is to receive a webhook, make a simple transformation, and send that data to one or multiple other apis.
All you need to do is create a project, add "Outbound lanes" to where you want to send your request, and use the project ingress url to receive the data.
I would like to monetize it to help pay the bills, but so far this is in free open beta.
The technologies used are Django + Bootstrap 5 + HTMX
This is a work in progress, but feedback would be appreciated. Both if you happened to have this problem (and how did you solve it), if you think this would be helpful, and what would be missing for a minimum viable product.
Thanks in advance! :)
I have the following flask route:
@dash_blueprint.route('/upload_blog_image', methods=['POST'])
@login_required
def upload_blog_image():
img = request.files.get('uploadBlogImage')
data = img.stream.read()
md5_name = hashlib.md5(data).hexdigest()
filename = f'{md5_name}.{img.mimetype.split("/")[-1]}'
blob_service_client = connect_to_blob()
blob_client = blob_service_client.get_blob_client(container='blog-images-dev', blob=filename)
blob_client.upload_blob(data)
token = get_create_sas_token(current_user.id, 'blog-images-dev')
access_url = f'{blob_client.url}?{token.sas_token}'
print(access_url)
#return redirect(url_for('blogging.editor'))
return render_template("blogging/editor.html", updated_url=access_url)
And in my html file:
<div class="modal fade" id="imageModal" tabindex="-1" role="dialog" aria-labelledby="imageModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="imageModalLabel">Image URL</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
{{ updated_url|e }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The updated_url is not showing in the modal after image upload.
Does anyone know what could be the problem ?
Hi,
I'm looking to use Jinja to vary a configuration file depending on whether a package is installed or not. I have installed syncthing on one of my servers, and found it too difficult to configure using ansible.
I want to change my pf.conf to add firewall rules depending on whether syncthing is installed our not. Normally I vary the rules based on role, like so:
{% if inventory_hostname in groups['poudriere'] %}
tcp_services = "{ ssh, http, https }"
{% endif %}
I've tried writing Jinja like this:
{% if syncthing in ansible.builtin.package_facts %}
tcp_services = "{ ssh, microsoft-ds, " $syncthing "}"
udp_services = "{ netbios-dgm, netbios-ns" $syncthing, $syncthing_discovery "}"
{% else %}
tcp_services = "{ ssh, microsoft-ds }"
udp_services = "{ netbios-dgm, netbios-ns }"
{% endif %}
Is there a way to make this work? Or should I look to a different approach
Thanks in advance
Hello, so I am trying to make a Search Bar using SQLAlchemy and Jinja, I have a database with Pokemons and when I type the letter "C" in the searchbar, I get a good return:
[<Pokemon 'Charmender'>]
But then I cant seem to display anything concerning this Pokemon. Here's what it looks like when I run it. And here's what the terminal says. I am this close to getting this right but I am totally lost right now.
Here's what my database looks like. I'll give both the region and pokemon database codes:
Regions:
from db import db
from sqlalchemy.orm import relationship
class Regions(db.Model):
__tablename__ = 'regions'
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String(80), unique=True, nullable=False)
superficie = db.Column(db.Integer)
#image = db.Column(db.String(80))
def __repr__(self):
return '<Region %r>' % self.nom
Pokemons:
from db import db
from sqlalchemy.orm import relationship
class Pokemons(db.Model):
__tablename__ = 'pokemons'
id = db.Column(db.Integer, primary_key=True)
nom = db.Column(db.String(80), unique=True, nullable=False)
region_id = db.Column(db.Integer, db.ForeignKey('regions.id'),
nullable=False)
#region = db.relationship('Regions',
# backref=db.backref('pokemon', lazy=True))
date_creation = db.Column(db.DateTime(), nullable=False)
#image = db.Column(db.String(80))
taille = db.Column(db.Integer)
poids = db.Column(db.Integer)
description = db.Column(db.String())
def __repr__(self):
return '<Pokemon %r>' % self.nom
Then here's the Python code:
@app.route('/search', methods=['GET', 'POST'])
def search():
if request.method == 'POST':
print('post method')
form = request.form
search_value = form['search_string']
print(search_value)
search = "%{}%".format(search_value).upper()
print(search)
results = Pokemons.query.filter(Pokemons.nom.like(search)).all()
print("oll")
print(results)
#Quand tu Γ©cris dans la search bar la lettre capitale "C", results retourne Pokemon 'Charmender'
return render_templa
... keep reading on reddit β‘Hey there, I need some help from someone who has more experience with salt, jinja and for loop.
What I am trying to do is to get is the first key from a nested apps grain - which is an app name [someapp1 and someapp2 in my case].
Example apps grain:
apps:
someapp1:
group: wheel
heap: 7000
use_hugepages: True
someapp2:
group: nobody
heap: 3000
use_hugepages: False
My testing salt state (just to test if minion would present the proper values):
{% for key, value in grains['apps'].items() %}
cmd_run_{{ key }}:
cmd.run:
- name: echo "key value: {{ key|e }}"
- name: echo "value value: {{ value|e }}"
{% endfor %}
No matter what I do I get:
failed: mapping values are not allowed in this context
What am I missing?
I am currently going to school for Full Stack Dev and the curriculum I am going through is teaching React and then React Native. I have a portfolio project, an IMDB kinda thing, I started creating with Bootstrap(the prior course) and I am wondering about how best to flesh it out.
I thought using Jinja would be a good idea since I have some experience with it and seems like it would make it easier to eventually pass user data from a database. The course wants us to use React and I'm wondering if it's better to use one or the other.
Flask
I have a Jinja template with a list of dictionaries. Order matters. I'd like to reduce the list or lookup values based on the keys/values of the dictionaries. Here's an example:
{% set ordered_dicts = [ { 'id': 'foo', 'name': 'My name is Foo' }, { 'id': 'bar', 'name': 'My name is Bar' } ]%}
If I have a variable some_id = 'foo'
, how do I get 'My name is Foo'
out of ordered_dicts
in my Jinja template?
I tried select()
and selectattr()
but couldn't figure them out based on the documentation. Here's what I tried:
{{ ordered_dicts|selectattr("id", "foo") }}
That outputs:
<generator object _select_or_reject at 0x10748d870>
I don't think I'm understanding the use of select()
and selectattr()
properly.
Do I need to iterate over the list and do the lookup manually?
Update:
As codegeek and gipi pointed out, I need to do something like this with the generator:
{{ ordered_dicts|selectattr("id", "foo")|list }}
The resulting error: TemplateRuntimeError: no test named 'foo'
, which clarifies how selectattr()
works. The second argument has to be one of the builtin tests. As far as I can tell, none of these tests will let me check whether the value associated with a key matches another value. Here's what I'd like to do:
{{ ordered_dicts|selectattr("id", "sameas", "foo")|list }}
But that doesn't work, since the sameas
test checks whether two objects are really the same object in memory, not whether two strings/numbers are equivalent.
So is it possible to pick an item based on a key/value comparison test?
Answer link : https://codehunter.cc/a/flask/how-to-select-reduce-a-list-of-dictionaries-in-flask-jinja
Hello there,
I'm doing Python web development in emacs using lsp-mode(I want to switch over to eglot-mode eventually when the pull-requests get pushed and html/css/js work automatically with elgot-mode, so keep this in mind) as the IDE for the Python and HTML files, which is working great. But when doing Jinja/Django specific syntax(for example in an HTML file), the auto-completion does not work? Is there an lsp-mode/eglot-mode for this to be used with use-package?
If not then is there a way to declare web-mode in a use-package, where this functionality can be set, in which the corresponding Jinja/Django engine is activated based on a corresponding hook?
I'd prefer to stick with the .py and .html extensions, but if that's not possible, the I could try out extensions like .djhtml to be used in the web-mode hook in the declared use-package.
Thanks in advance for the help!
I frequent this sub and try to help out and answer as many questions as I can. One area that I see most people struggling with is using some of the more advanced jinja filters such as select
, selectattr
and map
. In this post I will try to give some easy to understand examples of how to use these filters in order to filter lists and dictionaries in your Ansible playbooks.
What are tests?
In jinja a test is a template expression that evaluates to either True
or False
. Test are used to compare objects.
Jinja has a number of built-in tests but Ansible also provies some filters of their own:
https://jinja.palletsprojects.com/en/3.0.x/templates/#list-of-builtin-tests
https://docs.ansible.com/ansible/latest/user_guide/playbooks_tests.html
What are filters?
In jinja filters are used to modify/manipulate variables. For example converting strings from lowercase to uppercase or selecting items from a list.
Both jinja tests and filters run on on Ansible controller itself, not on the target host.
Select is used to filter a list by applying a test to each object in the list and only returning those items where the test succeeded. The reverse of select
is reject
that works the same way, only that it returns the objects that fail the test.
The select filter takes one or 2 arguments; the test to apply and an optional argument to that test:
{{ the_list_to_filter | select('name_of_the_test', 'optional_argument_to_test') }}
Let's say that you have a list of interface names and your want to filter out only the interfaces that start with eth
:
interfaces:
- eth0
- eth1
- wg0
- docker0
You could filter the list of interfaces using this expression:
- name: Print filtered interface list
ansible.builtin.debug:
msg: "{{ interfaces | select('regex', '^eth') | list }}"
TASK [debug]
ok: [localhost] => {
"msg": [
"eth0",
"eth1"
]
}
You may wonder about what the | list
at the and does here. Because the select filter returns a "generator object" you have to convert it to a list before printing it with debug
.
The select filter is similar to doing something like this in python:
filtered_interfaces = (interface for interface in interfaces if
... keep reading on reddit β‘Hello, I am new the JavaScripts and I need to incorporate some Java Scripts into my Python project for my searchbar. I need an autocomplete for it. The searchbar works, but whenever I add the Ajax/Java parts, my search results redirect to the '/' (main jinja page), and I do not know how to implement the JavaScripts into my search bar for the autocomplete search bar to work. Here's the JS:
/script.js
$(document).ready(function (){
var pokemons=[];
function loadPokemons(){
$.getJSON('/pokemons', function (data, status, xhr) {
for (var i =0; i < data.length; i++){
pokemons.push(data[i].nom)
}
});
};
loadPokemons();
$('#pokemon').autocomplete({
source: pokemons,
});
$('form').on('submit'), function (e){
$.ajax({
data: {
pokemons:$('#pokemons').val()
},
type: 'POST',
url: '/process'
})
.done(function (data){
if (data.error){
$('#result')
}
})
}
})
And here's the HTML:
/page_maitre.html (jinja page)
<form class="form-inline" >
<div class="form-group">
{{form.pokemons(class="form-control")}}
</div>
<button type="submit" class="btn btn-info">Submit</button>
</form>
<div id="result"></div>
</form>
<script src="/static/script.js"></script>
As for the Python, I believe here resides the main problem, but I do not know how to incorporate it:
The pokemonss app route, return a jsonify successfully and shows all the Pokemons successfully into a jsonify tab, which I believe is a small success.
Although I need to manually write the /pokemonss (with two ss) In order to get the Jsonify tab.
/main.py
@app.route('/pokemonss')
def pokeDic():
res = Pokemons.query.all()
liste_pokemons = [r.as_dict() for r in res]
return jsonify(liste_pokemons)
@app.route('/process', methods=['POST'])
def process():
pokemons = request.form['pokemons']
if pokemons:
return jsonify({'pokemons':pokemons})
r
... keep reading on reddit β‘I am currently trying to develop an app that has the same form present on all views. When I try to extend the template containing the form, I get an error saying that form is undefined in the child templates. I looked into context processors, but adding the extra {{form}} tag didn't seem to help (ie I got the same UndefinedError in Jinja).
I have a list with some data that I am trying to render to my Flask front-end using Jinja. I've successfully rendered some sample data, but I can't figure it out with the way my actual list data is formatted. Below is an example of my list format and what I have in my html. I'm trying to loop through the arrays in my list and show the data in individual div tags.
# List format
queryData =
{
'value1': [108, 35, 131],
'value2': [5, 79, 25],
'timestamp': ['Sep 29 2021', 'Sep 28 2021', 'Sep 27 2021']
}
# HTML Jinja code
{% for txn in queryData %}
<div class="transaction">
<div class="txnValue1">{{txn.value1}}</div>
<div class="txnValue2">{{txn.value2}}</div>
<div class="txnTimestamp">{{txn.timestamp}}</div>
</div>
{% endfor %}
Hi,
I have these lines in the urls.py
path('add-sales-invoice',Β SalesInvoiceCreateView.as_view(),Β name='add-sales-invoice'),
path('update-sales-invoice/<int:pk>/',Β SalesInvoiceUpdateView.as_view(),Β name='update-sales-invoice'),
In HTML Templet with jinja.
This works "{% url 'add-sales-invoice' %}"
But this does not. {% url 'update-sales-invoice/<int:pk>/' %}
It gives me an error of 'update-sales-invoice/<int' is not a registered namespace
but its a bit weird because I can access other pages in the same which means namespace is properly registered.
Am I missing something? :(
Representing over two years of work from the Pallets team and contributors, new major versions Flask, Werkzeug, Jinja, Click, ItsDangerous, and MarkupSafe have been released on May 11, 2021. Check out our announcement on our blog: https://palletsprojects.com/blog/flask-2-0-released/, and retweet it to spread the word on Twitter as well: https://twitter.com/PalletsTeam/status/1392266507296514048
Every project has significant changes, and while we don't anticipate breaking things, it may take some time for extensions and other projects to catch up. Be sure to use tools like pip-compile and Dependabot to pin your dependencies and control when you upgrade.
Overall changes to every project include:
Check out the changelog links for each project to see all of the great new features and changes. I've included some of the highlights here as well.
async def
views and callbacks.@app.post()
and @app.delete()
.multipart/form-data
is parsed 15x faster, especially for large file uploads.pgettext
.*
and ~
patterns are expandedHi, may I know where it goes wrong in my code as the expected value didn't show up.
{% for host in groups[group_name] %}
Host, Username, Privilege
{% for name in hostvars[host]['user_username'] %}
{% for is_priv in hostvars[host]['is_privilege'] %}
{{host}},{{name}},{{ is_priv }}
{% endfor %}
{% endfor %}
{% endfor %}
Code output:
Expected output
This is my playbook
- name: show u2
ios_command:
commands: show run | inc username
register: output3
# Split for per customer
- name: set value
set_fact:
output12: "{{output3.stdout[0].split('\n')}}"
cacheable: yes
- name: Check if customer is privilage or not.
set_fact:
user_username: "{{user_username + [item.split(' ')[1]] }} "
priv: "{{ mypriv }}"
is_privilege: "{{is_privilege}} + [ '{% if mypriv == 'privilege' %}True{% else %}False{% endif %}'] "
cacheable: yes
vars:
mypriv: "{{ item.split(' ')[2] }}"
loop: "{{ output12 }}"
Output12 output:
"output12": [
"username ciscoadmin privilege 15 password 0 admin",
"username ciscouser password 0 admin"
]
Thank you for the help :)
Hi
I am trying to run a task to ping ps shortcut to taskbar.
- name: Pin PS shortcut to taskbar
win_shell: (New-Object -com Shell.Application).NameSpace("C:\Windows\System32\WindowsPowershell\v1.0\).ParseName("powershell.exe").InvokeVerb("taskbarpin")
tags:
- install
- software
- pinPS
The command runs fine locally but when i run it through ansible win_shell I get this error.
I have tried all sorts of different "" or ''. Tried removing the "" from the Namespace part.
I have even tried creating a var called backslash and then using (backslash) instead of \ in the command.
How am I supposed to be able to use a backslash in a win_shell powershell command.
Is my only answer to create is as a ps1 file copy that over and then have it run that
Any advice appreciated
Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.