I'm totally new at web development and I am currently trying to create a little website. The goal of this site, is to show random quotes of some of my teachers. The main pages are actually working just fine (I can get random quotes of my whole database, and random quotes from every teacher). But, I wanted to show all the quotes on the same page, and it happens they just appear all on the same line... And it's quite embarrassing...
In my python code, I used "\n" between each quote, so each new one started on a new line. But, on my HTML code, when I pass this string, it seems to have no effect I all the quotes just follow themselves on one line....
I'm using a Flask application, and a python class:
for i in range(2, max):
inte = inte + citation.ClasseCitations('Classe/citations.json','Classe/profs.json', prof, i).corps + ' \n '
return render_template("integrale.html", citation=inte, auteur=prof)
In my HTML file, I use citation like this:
<p>{{ citation }}</p>
Try this :
for i in range(2, max):
inte = inte + citation.ClasseCitations('Classe/citations.json','Classe/profs.json', prof, i).corps + ' <br/> '
return render_template("integrale.html", citation=inte, auteur=prof)
I'm not able to comment, but try it with
<br/>
instead of
\n
this could work.
I'd try using a list object within your flask-app.
Then in your html:
{% for quote in quotes %}
{{quote}} <br>
{% endfor %}
More on jinja2's for-loops
http://jinja.pocoo.org/docs/2.9/templates/#for-loop
Related
I currently use txt editor to modify my email newsletter code that i send to vendors.
It is tedious, however it does allow for me to create a html table and edit it and send out to customers.
I thought it might be easier to code something that would allow me to type the input and the program would then give me and output of the formatted HTML code ready to copy and paste to my newsletter email service.
this is what i currently have, but it does not print the code with the necessary input values.
this is what i have so far
"""
VAN_REEFER = input("VAN OR REEFER OR POWER ONLY?")
PICKUP_LOCATION = input("WHERE DOES THIS PICKUP?")
PICKUP_TIME = input("WHAT TIME DOES THIS PICKUP?")
DROP_LOCATION = input("WHERE DOES THIS DROP?")
DROP_TIME = input("WHAT TIME DOES THIS DROP?")
ACCEPT_NOW = input("ACCEPT NOW RATE")
print ("""<tr>
<td>(VAN_REEFER)</td>
<td>(PICKUP_LOCATION)<br><b>(PICKUP_TIME)</b></br></td>
<td>(DROP_LOCATION)<br><b>DROP_TIME</b></br></td>
<TD><B>(ACCEPT_NOW)</B></TD>
<td>
<a href="mailto:Dispatch%40MYEMAIL.com?subject=%20%F0%9F%90%A2%20-%20%20-
PICK-
(PICKUP_TIME)
%20-%20-
(PICKUP_LOCATION)
%20
TO
%20-
(DROP_TIME)
-%20
(DROP_LOCATION)
DROP-
%20-%20
(VAN_REEFER)
%0A&body=
I%20HAVE%20A%20TRUCK%20FOR%20THIS%20LOAD-
%20%0A
MY%20RATE%20IS-
%20%0A
THIS%20IS%20MY%20ETA%20TO%20PICKUP%20THIS%20LOAD-
%20%0A
THIS%20IS%20MY%20PHONE%20NUMBER-
%20%0A">🐢<b>BID HERE</b>🐢</a>
</td>
</tr>
""")
"""
what i would like for this do is to take as many inputs that i want and when i am done it would recreate that code, with the different inputs that were entered by the end user. sometimes there might be 1 or 2 sets of inputs, sometimes there might be a dozen. once completed the program would compile each input into the code that i need to copy and paste to my email marketing service.
can someone help?
Take a look at template engines such as Jinja or mako.
You can write html templates like this (example is from this Jinja tutorial):
<p>My string: {{my_string}}</p>
<p>Value from the list: {{my_list[3]}}</p>
<p>Loop through the list:</p>
<ul>
{% for n in my_list %}
<li>{{n}}</li>
{% endfor %}
</ul>
and the template engine will dynamically replace the variables given in the double curly brackets {{}}. You can even create loops and conditions using {% ... %}.
I am attempting to create a file in simple website and then read the contents of the same in a variable inside a Django view function and parse the variable to the template to be displayed on web page.
However, when I print the variable, it appears the same on cmd as is in the original text file, but the output on the web page has no formattings but appears like a single string.
I've been stuck on it for two days.
Also I'm relatively new to django and self learning it
file1 = open(r'status.txt','w',encoding='UTF-8')
file1.seek(0)
for i in range(0,len(data.split())):
file1.write(data.split()[i] + " ")
if i%5==0 and i!=0 and i!=5:
file1.write("\n")
file1.close()
file1 = open(r'status.txt',"r+",encoding='UTF-8')
d = file1.read()
print(d) #prints on cmd in the same formatting as in text file
return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text
string**
<body>
{% block content %}
{{dat}}
{% endblock %}
</body>
Use the linebreaks filter in your template. It will render \n as <br/>.
use it like -:
{{ dat | linebreaks }}
from the docs:
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (<br>) and a new line followed by a
blank line becomes a paragraph break (</p>).
You can use linebreaksbr if you don't want <p> tag.
It's because in HTML newline is </br> in Python it is \n. You should convert it, before rendering
mytext = "<br />".join(mytext.split("\n"))
Depending of your needs and the file format you want to print, you may also want to check the <pre> HTML tag.
So I first create an array of all folders in a specific directory, I then pass that to my html file.
def test_yt_vid():
mylist = os.listdir(WD+r"static/"+YOUTUBE_FOLDER)
full_path = (WD+YOUTUBE_FOLDER)
return dict(mylist=mylist, full_path=full_path)
Next I look through that array to find what file has been selected.
<select name=list id="videolist" method="GET" action="/">
{% for mylist in mylist %}
<option value= "{{mylist}}" SELECTED>{{mylist}}</option>"
{% endfor %}
</select>
Next I use JS to get the specific value into a variable
$('#videolist').change(function () {
//console.log($("#videolist").val());
var fileInput = $("#videolist").val())};
So The problem is here, I'm not sure how I would go about passing that value into the following jinja code
<video id="videotesting1" class="video" width="300" height="240" autoplay loop controls="true">
<source src="{{url_for('static',filename='videoTest/' + 'testVid.mp4')}}" type="video/mp4">
</video >
I'm trying to replace 'testVid.mp4' with the variable fileInput from the JS, I tried using $("#videotesting1").attr("src","{{url_for('static',filename='videoTest/'" + fileInput +")}}");'
But no luck so far.
This is different to "How do you change video src using jQuery?" because I am trying to pass a jinja variable to HTML using js.
You have some wrong closed quotes. Take a look at filename, where you set 'videoTest/' plus some variable value (e.g x), which results in 'videoTest/'x. Do you notice it? The single quote closed after videoTest should appear after the variable fileInput. The correct way would be:
$("#videotesting1").attr("src","{{url_for('static',filename='videoTest/" + fileInput + "')}}");
When you modify the src, has by inspect element the src changed, but the desired video isn't being played? If so, try:
$("#videotesting1").load()
Take a look at what load does # JQuery docs.
Figure out the problem, the file name has to go outside the jinja code because it doesnt get rendered by jinja for some reason when the event happens.
$("#videotesting1").attr("src","{{url_for('static',filename='videoTest/')}}" + fileInput);
I'm working with flask and sqlalchemy to print a list in an html page. Code is below
Python code:
#app.route('/restaurants')
def showRestaurants():
restaurant = session.query(Restaurant.name)
return render_template('restaurants.html', restaurant = restaurant)
Html code:
<ul>
{% for i in range(0,9) %}
<li>
<strong>{% print(restaurant[i]) %}</strong>
</li>
{% endfor %}
</ul>
Page:
(u'Urban Burger',)
(u'Super Stir Fry',)
(u'Panda Garden',)
(u'Thyme for That Vegetarian Cuisine ',)
(u"Tony's Bistro ",)
(u"Andala's",)
(u"Auntie Ann's Diner ",)
(u'Cocina Y Amor ',)
(u'State Bird Provisions',)
So, what am I doing wrong? I have a database with restaurant names and wanna make a list of it but it seems impossible to decode it. I've already tried .encode() which print out an error says the variable encode is not define and when I put in create_engine encoding = 'acsii' simply does nothing. I appreciate any help.
SQLAlchemy's session.query returns a list of tuples. So, to display the name of each restaurant, you'd want to access the string in the first element of each tuple.
<strong>{% print(restaurant[i][0]) %}</strong>
encode('ascii') will work, but you have to apply it to the unicode string. The problem you have right now is that you are printing out a tuple not a string.
Instead, try referencing the restaurants like this:
restaurant[i][0].encode('ascii')
Even restaurant[i][0] might render correctly.
I'm trying to do something that I imagine must be trivial in mako, but I just can't figure out how I should procede and I'm finding the documentation pretty useless. I'm quite familiar with Python and DTL, but I just don't understand why this code is throwing a syntax error.
Basically, all I want to do is take in a datum object (just a small dictionary) and differently generate a link based on where the request is coming from. I know it would be trivial to do this in straight python and pass it in as context, but I'm really trying to warm up to mako. Any help would be hugely appreciated.
<%def name="courseware_link(datum)">
% if courseware in ${request.url}:
<a href=${request.url}[:${request.url}.find("courseware")+len("courseware")+1]+datum["url"]>
% else:
<a href=${request.host}+"/courses/"+datum["org"]+"/"+datum["course_ids"]+"/#/courseware/"+datum["url"]
% endif
</%def>
More specifically the syntax error is this:
(SyntaxError) invalid syntax (<unknown>, line 1) (u'if courseware in ${request.url}:pass') in file '/file' at line: 70 char: 1
and line 70 is the second line % if courseware...
You are mixing ${} with regular python in the if conditional and both a tags. Also, you cannot nest ${} inside ${}. You should probably refactor this code to be either out of the template or into a <% %> block, but something like this should work:
%if "courseware" in request.url:
<a href="${request.url[:request.url.find('courseware')+len('courseware')+1]+datum['url']}">
%else:
<a href="${request.host + '/courses/' + datum['org'] + '/' + datum['course_ids'] + '/#/courseware/' + datum['url']}">
%endif
Here is a refactored version:
<%def name="courseware_link(datum)">
<%
if "courseware" in request.url:
url = request.url[:request.url.find("courseware")+len("courseware")+1]
url += datum["url"]
else:
url = request.host + "/courses/" + datum["org"] + "/"
url += datum["course_ids"] + "/#/courseware/" + datum["url"]
%>
<a href="${url}">
</%def>
Furthermore you might want to use a routing package to generate your urls instead of building them manually like this, Django should provide something to automatically construct urls.