Search code examples
cookiecutterpyproject.toml

Cookiecutter: Add information to pyproject.toml according to template variable


In my cookiecutter template, I have the following question: "Do you want to use an internal repository? ["Yes", "No"].

If answered "Yes", I would like to add another table to my pyproject.toml configuration file.

[[tool.poetry.source]]
name = "internal_repo"
url = "https://internal_repo/simple"
default = true

What's the best way to do it?

EDIT: Include parts of the template and parts of the resulting file.

Template:

# pyproject.toml template

...

[[tool.poetry.source]]
name = "internal_repo1"
url = "https://internal_repo1/simple"
default = true

{% if cookiecutter.use_bloomberg == "Yes" %}
[[tool.poetry.source]]
name = "internal_repo2"
url = "https://internal_repo2/simple"
{% endif %}

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

Output if cookiecutter.use_bloomerg == "Yes"

# pyproject.toml

...

[[tool.poetry.source]]
name = "internal_repo1"
url = "https://internal_repo1/simple"
default = true


[[tool.poetry.source]]
name = "internal_repo2"
url = "https://internal_repo2/simple"




[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

Output if cookiecutter.use_bloomerg == "No"

# pyproject.toml

...

[[tool.poetry.source]]
name = "internal_repo1"
url = "https://internal_repo1/simple"
default = true





[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

I would like to have 1 blank line between the different sections in the pyproject.toml file.


Solution

  • You should not use spaces in your questions, as those are used as attributes of the cookiecutter object afterwards.

    So, what you want will look similar to this:

    // cookiecutter.json
    {
      "use_internal_repository": ["Yes", "No"]
    }
    
    # The file where you need to check
    {% if cookiecutter.use_internal_repository == "Yes" %}
    Yes, I want an internal repo!
    {% else %}
    No, thank you! I'm good.
    {% endif %}
    

    Keep in mind, that those template tags may lead to unwanted newlines. If you want to control that, you should use minus signs here and there. You could learn more about this here.