Search code examples
pythondictionaryweb2pynonetype

How to omit NoneType from Web2Py URLs with get vars


I know if can be accomplished with a few if statements and repeated code, but I was wondering if there's a more elegant way to handle this seeing as it's in my view and I don't like to have large code blocks in them. I have two buttons, Print and CSV. The URLs they link to are set up like the following:

<a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'print', 'header':header, 'student':student})}}" target="_blank">Print</a>
<a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'csv', 'header':header, 'student':student})}}" target="_blank">Download CSV</a>

The problem I'm having here is that both student and header can be None, but they can't both not be None, and I'm looking for a one-liner solution to the problem. Like I said, I'm aware I can just make some if/else blocks like:

{{if student:}}
    <a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'print', 'student':student})}}" target="_blank">Print</a>
    <a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'csv', 'student':student})}}" target="_blank">Download CSV</a>
{{elif header:}}
    <a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'print', 'header':header})}}" target="_blank">Print</a>
    <a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'csv', 'header':header})}}" target="_blank">Download CSV</a>
{{else:}}
    <a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'print'})}}" target="_blank">Print</a>
    <a class="btn btn-primary" href="{{=URL('teacher', 'classdata', args=request.args, vars={'view':'csv'})}}" target="_blank">Download CSV</a>
{{pass}}

But that looks awful for a view. If there's nothing more concise, bummer, I can roll with that, but I'd prefer something one or two lines that I can take with me to the next time this is a thing


Solution

  • You can use a dictionary comprehension to filter out the None values:

    vars={k:v for k,v in [('view', 'print'), ('header', header), ('student', student)] if v is not None}