# -*- coding: utf-8 -*-
"""
rio.utils.inject
~~~~~~~~~~~~~~~~
"""

import re

ENV_PLACEHODLER = re.compile(r'{{\s?(\w+)\s?}}')

def format_config(data, env):
    """
    Format data with given env.
    :param data: a string/integer/float/boolean/list/dict object.
    :param env: a dictionary.
    :return: return formatted data.
    `format_config` will try to format strings contained env placeholder `{{ ENV_KEY }}`.
    If `ENV_KEY` does not exist in env, then this function will trhow assertion error.
    """
    if isinstance(data, list):
        return [format_config(datum, env) for datum in data]
    elif isinstance(data, dict):
        return {
            format_config(key, env): format_config(value, env)
            for key, value in data.items()
        }
    elif isinstance(data, str):
        def replace(match):
            assert env.get(match.group(1))
            return env.get(match.group(1))
        return ENV_PLACEHODLER.sub(replace, data)
    else:
        return data

@@ -60,16 +60,44 @@
 ~~%0A%22%22%22%0A%0A
+from jinja2 import Template%0A
 import r
@@ -164,24 +164,36 @@
 mat_
-config(data, env
+template(string='', env=None
 ):%0A 
@@ -231,16 +231,159 @@
 en env.%0A
+%0A    Example:%0A%0A        %3E%3E%3E format_template('http://%7B%7B SERVICE_HOST %7D%7D/webhook/exec', %7B'SERVICE_HOST': 'app'%7D)%0A        http://app/webhook/exec%0A%0A
     :par
@@ -394,55 +394,37 @@
 ata:
- a
  string
-/integer/float/boolean/list/dict objec
+ with placeholder in i
 t.%0A 
@@ -482,20 +482,22 @@
 rmatted 
-data
+string
 .%0A    %60f
@@ -683,484 +683,62 @@
     
-if isinstance(data, list):%0A        return %5Bformat_config(datum, env) for datum in data%5D%0A    elif isinstance(data, dict):%0A        return %7B%0A            format_config(key, env): format_config(value, env)%0A            for key, value in data.items()%0A        %7D%0A    elif isinstance(data, str):%0A        def replace(match):%0A            assert env.get(match.group(1))%0A            return env.get(match.group(1))%0A        return ENV_PLACEHODLER.sub(replace, data)%0A    else:%0A        return data
+env = env or %7B%7D%0A    return Template(string).render(**env)
 %0A

refactor template.