Mako giving SyntaxError on valid code?
I'm trying to use a block of code within a mako template, yet no matter what I put in the block, Mako is adamant it's a syntax error.
Here's a snippet of the block in question:
<td class="col_sm_space"> </td>
<%
if session.dist == "metric":
delta_distance = "%.2fkm" % (trk["d_distance"] / 1000.0)
delta_fuel = "%.2fl" % (trk["d_fuel"])
delta_co2 = "%.2fg" % (trk["d_co2"])
delta_co2_rate = "%.2fg/l" % trk["d_co2_rate"])
trip_av_speed = "%dkm/h" % int(trk["trip_av_speed"])
trip_peak_speed 开发者_开发技巧= "%dkm/h" % int(trk["trip_peak_speed"])
%>
<td class="col_field" title="${delta_distance}">${trk["trip_distance"]}</td>
I'm getting the syntax error on the if session.dist == "metric":
line, although I could replace this with anything (Such as foo = "bar"
) and it still gives me the error.
Mako is returning:
SyntaxException: (SyntaxError) invalid syntax (line 5) ('if session.dist == "metric":\\n delta_distance = ') in file '<snipped>' at line: 271 char: 9\n, referer: <snipped>
Line 271
is the opening <%
. Char 9
would be the beginning of the if
on the next line, apparently.
Oddly, I'm using this exact same setup on other pages, and it's fine with those - just not here.
Anything glaringly obvious I'm missing here?
I had a really frustrating experience with this. In my case, at least, the error report was just completely wrong. It pointed to the first line of a python block, like yours, when the actual error was in a different python block, 50 lines later.
Likely, you have a simple syntax error like bad indentation or a missing colon after an if statement... I can't give you any better debugging advice than going through your python with a fine-toothed comb. If it's possible to unit-test your python blocks outside of Mako, that might be helpful.
My experience was that I had this if syntax:
% if ${use_force_ssl} == 1:
Instead, it was supposed to be like this:
% if use_force_ssl == 1:
Hope this helps someone.
This was asked a very long time ago but for the record there is a missing left paren, "(", on this line, its not clear if that is causing the problem but it seems likely:
delta_co2_rate = "%.2fg/l" % trk["d_co2_rate"])
Should be at least:
delta_co2_rate = "%.2fg/l" % (trk["d_co2_rate"])
In mako templates,
when you are using a conditional statement eg if, for etc, it should be like this:
% if condition
some code
%endif
And for assigment, you have to embed that thing in <% %>
If you will follow this, your code will run.
精彩评论