Skip to content

Custom Templates

One of the powerful features of the datamodel-code-generator is the ability to use custom templates with the --custom-template-dir option. This option allows you to provide a directory containing Jinja2 templates for customizing the generated code. In this document, we'll explore how to use this option and provide an example to help you understand its usage.

Usage

To use the --custom-template-dir option, you'll need to pass the directory path containing your custom templates as an argument. The command will look like this:

$ datamodel-codegen --input {your_input_file} --output {your_output_file} --custom-template-dir {your_custom_template_directory}
Replace {your_input_file}, {your_output_file}, and {your_custom_template_directory} with the appropriate paths.

Example

Let's say you want to generate a custom Python data model from a JSON Schema file called person.json. You want the generated data model to include a custom comment at the top of the file. To achieve this, you can create a custom template using Jinja2.

First, create a directory called custom_templates in your project directory. Inside this folder, create another folder called pydantic. Now, inside the pydantic folder, create a new file called BaseModel.jinja2 with the following content:

custom_templates/pydantic/BaseModel.jinja2

# This is a custom comment generated with custom_template!!

class {{ class_name }}({{ base_class }}):
{%- for field in fields %}
    {{ field.name }}: {{ field.type_hint }}
{%- endfor -%}

This custom template includes the custom comment at the top and replicates the default rendering behavior of the BaseModel.jinja2 template from the Datamodel Code Generator.

Now, you can use the --custom-template-dir option to generate the data model with your custom template:

$ datamodel-codegen --input person.json --output person.py --custom-template-dir custom_templates

The generated person.py file will now include your custom comment at the top:

person.py

# generated by datamodel-codegen:
#   filename:  person.json
#   timestamp: 2023-04-09T05:36:24+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel

# This is a custom comment generated with custom_template!!


class Model(BaseModel):
    name: Optional[str]
    age: Optional[int]

In this example, we kept it simple, but you can create more complex custom templates by copying the default templates Use the default templates as a reference for understanding the structure and available variables, and customize the code generation process according to your specific requirements.