def clean_up_whitespace_in_template_output(text):
    """Remove some excess whitespace from using Django templates for YAML."""

    ret = []
    for line in text.split("\n"):
        # Truly empty lines are likely intentional, so keep them
        if not line:
            ret.append("")
            continue

        # If the line consists entirely of trailing whitespace, it is likely an
        # artifact of template tag formatting, so drop it.
        line = line.rstrip()
        if not line:
            continue

        ret.append(line)

    text = "\n".join(ret)
    if not text.endswith("\n"):
        text += "\n"
    return text