0

I am using Jinja2 with FastAPI.

I would like to use a template table made with DataTables wherein I need to customize the table values for different pages using the same template table.

In one of the tables I have to convert the data of first column into a link (href tag).

For this I use the render method of DataTables for columndefs so that in my data-table.html I have:

new DataTable('#myTable', {
    ...
    columnDefs: [{{ columndefs|e }}]
});

and in the parent template I set columndefs as local variable:

{% set columndefs = """
        {
            targets: 0,
            render: (data, type, row) => '<a href="/api/'+data+'">'+data+'</a>',
        }
    """
%}
...
{% include "data-table.html" %}

The problem is that this throws an error:

    {% set columndefs = """
jinja2.exceptions.UndefinedError: 'api' is undefined

I think this is because the templating has problems by mixed use of " and '.

How can I correctly use href in columndefs so that it works?

2
  • Just a suggestion, if you've got control of the data being returned from the API (or whatever function creates the data) is to send a preformed URL rather than create it in Jinja. Been down a similar road, and while Jinja is pretty powerful, I've found having all the data and attributes ready, really simplifies the Jinja templates and makes them more maintainable and reusable. Commented Nov 12, 2024 at 21:43
  • Thanks, this is a good solution. But meanwhile I solved it by passing the columndefs as context parameter on server side Commented Nov 13, 2024 at 8:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.