views:

82

answers:

2

In a web2py view, how do I comment out server-side code? In ASP.NET, I can surround any HTML or code tags with <%-- and --%> and that block will not be compiled or sent to the client. Velocity does the same thing with #* and *#. Is there an equivalent in web2py?

ASP.NET

<div>
    <p><%=foo.bar%></p>
    <%-- don't print twice! <p><%=foo.bar%></p> --%>
</div>

web2py

<div>
    <p>{{=foo.bar}}</p>
    ??? don't print twice! <p>{{=foo.bar}}</p> ???
</div>

EDIT: Fixed web2py code tags.


Problem with block comments

An exception is thrown if {{'''...'''}} and {{"""..."""}} are used with code blocks inside. A non-ideal workaround that leaves the code mostly unchanged is removing the double-braces from the commented-out code blocks.

HTML

{{'''{{somefunction(42)}}'''}}

Error

Traceback (most recent call last):
  File "gluon/restricted.py", line 176, in restricted
  File "gluon/restricted.py", line 163, in compile2
  File "C:\development\web2py\applications\SpaceCorps/views\default/index.html", line 74
    '''{{somefunction(42)\nresponse.write("'''}}\r\n\t\t\r\n\t</div>\r\n</div>\n\t</body>\n</html>\n",escape=False)
                                          ^
SyntaxError: invalid syntax

Generated View code

'''{{somefunction(42)\nresponse.write("'''}}\r\n\t\t\r\n\t</div>\r\n</div>\n\t</body>\n</html>\n",escape=False)

Problem with single-line comment

{{#}} successfully comments, but also doesn't quite work as expected. This may be more difficult to fix, however, and should be easy to work around. The following HTML will render two end brackets to the final HTML, while I think it should render nothing.

HTML

{{#{{somefunction(42)}}}}
+4  A: 

In web2py you enclose code in {{ }} not <% %>. You can comment is as you would comment Python code. For single line code you do

{{#.....}}

for multiline

{{'''......'''}}

or

{{"""......"""}}
mdipierro
Thanks! I suppose I should have tried that first. Having real Python code in my templates is the biggest reason I chose web2py over any other framework.
MikeWyatt
+1  A: 

you can do as Massimo suggested, or often I just comment out the resulting HTML for temporary changes:

Plumo