Search code examples
web2pycanonical-link

web2py insert <link rel=canonical> into header


In web2py, from within a view, how do I insert a <link rel="canonical" href="..."> link into the header of the page. I know I can add a link tag with rel="stylesheet" using e.g. {{response.files.append(URL('static','css/base.css'))}}. Is there an equivalent for rel="canonical"?


Solution

  • One option is to create a block in the head section of the layout.html view:

    {{block canonical}}{{end}}
    

    Then in any view where you want to set the canonical link:

    {{block canonical}}
    <link rel="canonical" href="...">
    {{end}}
    

    A simpler option would be to include the following in the head of layout.html:

    {{if response.canonical:}}
    <link rel="canonical" href="{{=response.canonical}}">
    {{pass}}
    

    Then anywhere in a model or controller file you can do:

    response.canonical = '...'