I am new to both Python (and django) – but not to programming.
I am having no end of problems with identation in my view. I am trying to generate my html dynamically, so that means a lot of string manipulation. Obviously – I cant have my entire HTML page in one line – so what is required in order to be able to dynamically build an html string, i.e. mixing strings and other variables?
For example, using PHP, the following trivial example demonstrates generating an HTML doc containing a table
<?php
$output = '<html><head><title>Getting worked up over Python indentations</title></head><body>';
output .= '<table><tbody>'
for($i=0; $i< 10; $i++){
output .= '<tr class="'.(($i%2) ? 'even' : 'odd').'"><td>Row: '.$i;
}
$output .= '</tbody></table></body></html>'
echo $output;
I am trying to do something similar in Python (in my views.py), and I get errors like:
EOL while scanning string literal (views.py, line 21)
When I put everything in a single line, it gets rid of the error.
Could someone show how the little php script above will be written in python?, so I can use that as a template to fix my view.
[Edit]
My python code looks something like this:
def just_frigging_doit(request):
html = '<html>
<head><title>What the funk<title></head>
<body>'
# try to start builing dynamic HTML from this point onward...
# but server barfs even further up, on the html var declaration line.
[Edit2]
I have added triple quotes like suggested by Ned and S.Lott, and that works fine if I want to print out static text. If I want to create dynamic html (for example a row number), I get an exception – cannot concatenate ‘str’ and ‘int’ objects.
Don’t do this.
Use Django’s templates. They work really, really well. If you can’t figure out how to apply them, do this. Ask a question showing what you want to do. Don’t ask how to make dynamic HTML. Ask about how to create whatever page feature you’re trying to create. 80% of the time, a simple
{%if%}or{%for%}does everything you need. The rest of the time you need to know how filters and the built-in tags work.Use
string.Templateif you must fall back to “dynamic” HTML. http://docs.python.org/library/string.html#template-strings Once you try this, you’ll find Django’s is better.Do not do string manipulation to create HTML.
Correct. You cannot.
You have three choices.
Convert the int to a string. Use the
str()function. This doesn’t scale well. You have lots of ad-hoc conversions and stuff. Unpleasant.Use the
format()method of a string to insert values into the string. This is slightly better than complex string manipulation. After doing this for a while, you figure out why templates are a good idea.Use a template. You can try
string.Template. After a while, you figure out why Django’s are a good idea.my_template.html
views.py
I think that’s all you’d need for a mockup.