Ejemplo n.º 1
0
def render_file_template(template_path,
                         use_defaults=False,
                         extra_context=None):
    """Render a single-file template with Cookiecutter.

    Currently this function only renders a file using default values defined
    in a ``cookiecutter.json`` file.

    Parameters
    ----------
    template_path : `str`
        Path to the file template. There should be a
        ``cookecutter.json`` in the same directory as the template file.
        This JSON file is used to define a provide defaults for the template's
        variables.
    use_defaults : `bool`, optional
        Disables Sphinx from interactively prompting for context variables, if
        `True`.
    extra_context : `dict`, optional
        Optional dictionary of key-value pairs that override defaults in the
        ``cookiecutter.json`` file.

    Returns
    -------
    rendered_text : `str`
        Content rendered from the template and ``cookiecutter.json`` defaults.
    """
    logger = logging.getLogger(__name__)
    logger.debug('Rendering file template %s', template_path)

    # Get variables for rendering the template
    template_dir = os.path.dirname(template_path)
    context_file = os.path.join(template_dir, 'cookiecutter.json')
    context = generate_context(context_file=context_file)
    context['cookiecutter'] = prompt_for_config(context, use_defaults)

    if extra_context is not None:
        context['cookiecutter'].update(extra_context)

    # Jinja2 template rendering environment
    env = StrictEnvironment(
        context=context,
        keep_trailing_newline=True,
    )
    env.loader = FileSystemLoader(template_dir)

    try:
        tmpl = env.get_template(os.path.basename(template_path))
    except TemplateSyntaxError as exception:
        # Disable translated so that printed exception contains verbose
        # information about syntax error location
        exception.translated = False
        raise
    rendered_text = tmpl.render(**context)

    return rendered_text
Ejemplo n.º 2
0
    def _execute(self):
        env = StrictEnvironment(context=self.context)

        env.loader = FileSystemLoader(self.file_system_loader)
        template = env.get_template(self.operator_dict['template_path'])

        jinja_context = (self.operator_dict['context']
                         if 'context' in self.operator_dict else {})

        if 'extra_context' in self.operator_dict:
            jinja_context.update(self.operator_dict['extra_context'])

        output_from_parsed_template = template.render(
            **{self.context_key: jinja_context})

        with open(self.operator_dict['output_path'], 'w') as fh:
            fh.write(output_from_parsed_template)

        return self.operator_dict['output_path']