Beispiel #1
0
def test_comments():

    liq = Liquid("""{% mode compact %}
4
{% comment %}
1
2
{% endcomment %}
5
""",
                 liquid_loglevel='debug')
    assert liq.render() == '4# 1\n# 25'

    liq = Liquid("""{% mode compact %}
4
{% comment // %}
1
2
{% endcomment %}
5
""")
    assert liq.render() == '4// 1\n// 25'

    liq = Liquid("""{% mode compact %}
4{# aa #}
{% comment /* */ %}
1
2
{% endcomment %}
5
""")
    assert liq.render() == '4/* 1 */\n/* 2 */5'
Beispiel #2
0
def test_include_extends_render_stacks(HERE):

    liquid = Liquid("""
    {{%- mode compact %}}
    {{% extends {0}/templates/extends.liq %}}
    {{% block b2 %}}
    {{% include "{0}/templates/include1.liq" x %}}
    {{{{x}}}}
    {{% endblock %}}
    """.format(HERE),
                    liquid_loglevel='debug')
    # see if I have render stacks correct:
    with pytest.raises(LiquidRenderError) as exc:
        liquid.render(x={})  # can't do {} * 10

    stream = LiquidStream.from_string(str(exc.value))
    _, tag = stream.until(
        ["unsupported operand type(s) for *: 'dict' and 'int'"],
        wraps=[],
        quotes=[])
    assert bool(tag)
    _, tag = stream.until(["Template call stacks:"], wraps=[], quotes=[])
    assert bool(tag)
    _, tag = stream.until(["File <LIQUID TEMPLATE SOURCE>"])
    assert bool(tag)
    _, tag = stream.until(["> 5.     {% include"])
    assert bool(tag)
    _, tag = stream.until(["templates/include1.liq"], wraps=[], quotes=[])
    assert bool(tag)
    _, tag = stream.until(["> 1. {% assign"], wraps=[], quotes=[])
    assert bool(tag)
    _, tag = stream.until(["Compiled source"], wraps=[], quotes=[])
    assert bool(tag)
    _, tag = stream.until(["> 33."], wraps=[], quotes=[])
    assert bool(tag)
Beispiel #3
0
def test_cycle(debug):

    liquid = Liquid("""
{%- for i in range(10): -%}
{%- cycle 'a','b','c' -%}
{%- endfor -%}
""")
    liquid.render() == 'abcabcabca'
Beispiel #4
0
def test_python():
    liq = Liquid("{% python _liquid_ret_append('123') %}",
                 liquid_loglevel='debug')
    assert liq.render() == '123'

    liq = Liquid("""
{%- python -%}
import math
_liquid_ret_append(math.ceil(1.1))
{%- endpython -%}""",
                 liquid_loglevel='debug')
    assert liq.render() == '2'
Beispiel #5
0
class TemplateLiquid(Template):
    """@API
	liquidpy template wrapper.
	"""
    def __init__(self, source, **envs):
        """
		Initiate the engine with source and envs
		@params:
			`source`: The souce text
			`envs`: The env data
		"""
        super(TemplateLiquid, self).__init__(source, **envs)
        self.envs['__engine'] = 'liquid'
        self.engine = Liquid(source, **self.envs)
        self.source = source

    def _render(self, data):
        """
		Render the template
		@params:
			`data`: The data used for rendering
		@returns:
			The rendered string
		"""
        return self.engine.render(**data)
Beispiel #6
0
def render_md(books):
    # load template from a file
    liq = Liquid('template/README.template.md', liquid_from_file=True)
    md = liq.render(books=books)

    with open("README.md", 'w') as f:
        f.write(md)
Beispiel #7
0
    def make_config(self, filename, template_directory=None):
        """
        Make the configuration file for this production.

        Parameters
        ----------
        filename : str
           The location at which the config file should be saved.
        template_directory : str, optional
           The path to the directory containing the pipeline config templates.
           Defaults to the directory specified in the asimov configuration file.
        """


        if "template" in self.meta:
            template = f"{self.meta['template']}.ini"
        else:
            template = f"{self.pipeline}.ini"

        try:
            template_directory = config.get("templating", "directory")
            template_file = os.path.join(f"{template_directory}", template)
        except:
            from pkg_resources import resource_filename
            template_file = resource_filename("asimov", f'configs/{template}')
        
        config_dict = {s: dict(config.items(s)) for s in config.sections()}

        with open(template_file, "r") as template_file:
            liq = Liquid(template_file.read())
            rendered = liq.render(production=self, config=config)

        with open(filename, "w") as output_file:
            output_file.write(rendered)
Beispiel #8
0
def render(*args, **kwargs):
    """
    Renders the template with the variables and filters.
    """
    template = TEMPLATE_CONTAINER.element.value
    variables = {}
    try:
        exec(VARIABLES_CONTAINER.element.value, variables)
    except Exception as e:
        _error(f"Something wrong when evaluating variables: \n{e}")
        return

    filters = {}
    try:
        exec(FILTERS_CONTAINER.element.value, filters)
    except Exception as e:
        _error(f"Something wrong when evaluating filters: \n{e}")
        return

    mode = MODE_CONTAINER.element.value
    _remove_class(RENDERED_CONTAINER, "bg-red-100")
    try:
        liq = Liquid(template, from_file=False, mode=mode, filters=filters)
        RENDERED_CONTAINER.element.value = liq.render(**variables)
    except Exception as e:
        _error(f"Something wrong when rendering: \n{e}")
Beispiel #9
0
def generate_file(details_file, template_file, output_file, base_url, log_level=''):
    with open(details_file) as f:
        _lists = json.load(f)
    _lists = make_safe_dict(_lists)
    liq = Liquid(template_file, liquid_from_file=True, liquid_loglevel=log_level)
    rendered = liq.render(lists=_lists, base_url=base_url)
    with open(output_file, 'w') as f:
        f.write(rendered)
Beispiel #10
0
def test_if_single():
    liq = Liquid("""
{% if a == 1 %}
abc{{b}}
{% endif %}
""")

    assert liq.render(a=1, b=2) == '\n\nabc2\n\n'
Beispiel #11
0
def test_init(HERE):
    with pytest.raises(FileNotFoundError):
        Liquid("a", liquid_from_file=True)

    tpl = HERE / 'templates' / 'parent5.liq'
    with tpl.open() as f:
        liq = Liquid(f, liquid_from_stream=True)

    assert liq.render() == "empty block"
def run(template="static/README.md",
        bib_directory="bib",
        output="README.md",
        quiet=False):
    """
    Parse .bib files (bib_directory), sort them, insert them into the template
    (template), then write them to a file (output).

    :arg quiet: If true, silence all status messages.
    """

    _verbose = not quiet

    if _verbose:
        print("📖 Reading *.bib files in {0}".format(bib_directory))

    _references = []

    for dir in os.listdir(bib_directory):
        for file in os.listdir(os.path.join(bib_directory, dir)):
            _references.append(
                Reference.load(os.path.join(bib_directory, dir), file))

    biblio = Bibliography(_references, verbose=_verbose)

    TOC_PAPERS_BY_YEAR = biblio.create_toc_papers_by_year()
    TOC_PAPERS_BY_TOPIC = biblio.create_toc_topics()
    PAPERS_BY_YEAR = biblio.create_papers_by_year_list()
    PAPERS_BY_TOPIC = biblio.create_topics_list()

    # TODO: Create a section for `Algorithms`
    ALGORITHMS = []

    if _verbose:
        print("📜 Reading template: {0}".format(template))

    with open(template, "r") as fh:
        readme = fh.read()

    if _verbose:
        print("✍️ Rendering new copy of {0}".format(output))

    liq = Liquid(readme)
    ret = liq.render(
        toc_papers_by_year=TOC_PAPERS_BY_YEAR,
        toc_papers_by_topic=TOC_PAPERS_BY_TOPIC,
        papers_by_year=PAPERS_BY_YEAR,
        papers_by_topic=PAPERS_BY_TOPIC,
    )

    if _verbose:
        print("💾 Saving {0}".format(output))

    # TODO: Use the built-in file handler for liquid.
    with open(output, "w") as fh:
        fh.write(ret)
Beispiel #13
0
def test_find(set_default_jekyll):
    liq = Liquid('{{ obj | find: "a", 1 }}')
    out = liq.render(obj=[
        {
            "a": 1,
            "b": 2
        },
        {
            "a": 2,
            "b": 4
        },
    ])
    assert out == "{'a': 1, 'b': 2}"

    out = liq.render(obj=[])
    assert out == "None"

    out = liq.render(obj=[{}])
    assert out == "None"
Beispiel #14
0
def test_multiline_support(debug_on):
    liq = Liquid("""{% mode compact %}
{{ a | @append: ".html"
     | @append: ".txt"
     | @append: ".gz"}}
""")
    assert liq.render(a='test') == "test.html.txt.gz"

    liq = Liquid("""{% mode compact %}
{% if a == "test" or
      a == "text" %}
{{a}}
{% endif %}
""")
    assert liq.render(a='test') == "test"

    liq = Liquid("""{% mode compact %}
{# if a == "test" or
      a == "text" #}
""")
    assert liq.render(a='test') == ""
Beispiel #15
0
def test_raw():
    liq = Liquid("""{% mode compact %}
    {% raw %}
4{# aa #}
{% comment /* */ %}
1
2
{% endcomment %}
5
{% endraw %}
""")
    assert liq.render(
    ) == '4{# aa #}\n{% comment /* */ %}\n1\n2\n{% endcomment %}\n5'
Beispiel #16
0
def test_include():
    liq = Liquid(f"{{% include {HERE}/templates/include1.liq x=x %}}{{{{x}}}}")
    assert liq.render(x=1) == '81'

    with pytest.raises(LiquidRenderError):
        Liquid(f"{{% include {HERE}/templates/include1.liq %}}{{{{x}}}}"
               ).render()

    with pytest.raises(LiquidSyntaxError):
        Liquid(f"{{% include {HERE}/templates/include1.liq , %}}").render()

    with pytest.raises(LiquidSyntaxError):
        Liquid(f"{{% include {HERE}/templates/include1.liq 9 %}}").render()
Beispiel #17
0
def test_include_config_switching(HERE):
    # test config switches in different parsers/files
    master = f"""
    {{% config mode=loose, loglevel=debug %}}
    {{{{1}}}}
    {{% include {HERE}/templates/parent5.liq %}}{{# in compact mode, loglevel=info #}}
    {{{{2}}}}"""
    liq = Liquid(master)
    assert LOGGER.level == 10
    #                                                     we should go back
    #                                                     to loose mode
    assert liq.render() == '\n    \n    1\n    empty block\n    2'
    # loglevel should not be changed
    assert LOGGER.level == 10
Beispiel #18
0
def test_for():
    liq = Liquid("""
    {%- for i in `x | range` -%}
{{i}}
    {%- endfor -%}
""",
                 liquid_loglevel='debug')
    assert liq.render(x=10) == '0123456789'

    liq = Liquid("""
    {%- for i, a in `x | enumerate` -%}
{{i}}{{a}}
    {%- endfor -%}
""")
    assert liq.render(x=['a', 'b', 'c']) == '0a1b2c'

    liq = Liquid("""
    {%- for k, v in x.items() -%}
{{k}}{{v}}
    {%- endfor -%}
""")
    assert liq.render(x={'a': 1, 'b': 2, 'c': 3}) == 'a1b2c3'

    liq = Liquid("""
    {%- for k, v in x.items() -%}
{%- if forloop.first -%}
First: {{k}},{{v}},{{forloop.index}},{{forloop.index0}},{{forloop.rindex}},{{forloop.rindex0}},{{forloop.length}}
{%- elif forloop.last -%}
Last: {{k}},{{v}},{{forloop.index}},{{forloop.index0}},{{forloop.rindex}},{{forloop.rindex0}},{{forloop.length}}
{%- endif -%}
    {%- endfor -%}
""")
    assert liq.render(x={
        'a': 1,
        'b': 2,
        'c': 3
    }) == 'First: a,1,1,0,3,2,3Last: c,3,3,2,1,0,3'
Beispiel #19
0
def test_nested_for(debug):
    liq = Liquid("""{% mode compact %}
{% for i in "a" %}
  {% for j in "c", "d" %}
    {% for k in "e", "f", "g" %}
    {{i}}-{{j}}-{{k}}-{{forloop.length}}/
    {% endfor %}
    {{forloop.length}}/
  {% endfor %}
  {{forloop.length}}/
{% endfor %}
""",
                 liquid_loglevel='debug')
    assert liq.render(
    ) == 'a-c-e-3/a-c-f-3/a-c-g-3/2/a-d-e-3/a-d-f-3/a-d-g-3/2/1/'
Beispiel #20
0
def test_render_error():
    liq = Liquid("""{% for i in a %}{{i}}{%endfor%}
1
2
3
4
5
6
""",
                 liquid_loglevel='info')
    with pytest.raises(LiquidRenderError):
        liq.render()

    liq = Liquid("""{% for i in a %}{{i}}{%endfor%}
1
2
3
4
5
6
""",
                 liquid_loglevel='debug')
    with pytest.raises(LiquidRenderError):
        liq.render(b=1)
Beispiel #21
0
    def create_issue(cls, repository, event_object, issue_template=None):
        """
        Create an issue for an event.
        """

        if issue_template:
            with open(issue_template, "r") as template_file:
                liq = Liquid(template_file.read())
                rendered = liq.render(event_object=event_object,
                                      yaml=event_object.to_yaml())
        else:
            rendered = event_object.to_yaml()

        repository.issues.create({
            'title': event_object.name,
            'description': rendered
        })
Beispiel #22
0
def test_include_extends(HERE, debug):

    liquid = Liquid("""
    {{%- mode compact %}}
    {{% extends {0}/templates/extends.liq %}}
    {{% block b2 %}}
    {{% include "{0}/templates/include1.liq" x %}}
    {{{{x}}}}
    {{% endblock %}}
    """.format(HERE),
                    liquid_loglevel='debug')

    # variable now not allowed to be modified in included template
    assert liquid.render(x=1) == 'empty blockabc81hij'
    #assert liquid.render(x = 1) == 'empty blockabc10hij'

    # make sure shared code only inserted once
    assert str(liquid.parser.shared_code).count(
        "# TAGGED CODE: _liquid_dodots_function") == 1

    # compiled code:
    """
Beispiel #23
0
def test_expression():
    liq = Liquid("{{a.a-b}}", liquid_loglevel='debug')
    assert liq.render(a={'a-b': 1}) == '1'

    liq = Liquid("{{a.a-b[0].x, b.c[1], b['c[1]']}}")
    assert liq.render(a={'a-b': [{
        'x': 2
    }]}, b={
        'c': [0, 3],
        'c[1]': 'x'
    }) == "(2, 3, 'x')"

    liq = Liquid("{{a | @abs}}")
    assert liq.render(a=-1) == '1'

    liq = Liquid("{{a, b | *@at_least}}")
    assert liq.render(a=4, b=5) == '4'
    liq = Liquid("{{a, b | *@plus}}")
    assert liq.render(a=4, b=5) == '9'

    liq = Liquid("{{a | .a-b[0].x}}")
    assert liq.render(a={'a-b': [{'x': 2}]}) == "2"
Beispiel #24
0
import yaml
from liquid import Liquid
from unidecode import unidecode
import sys

dictionary = sys.argv[1]
template = sys.argv[2]

with open(dictionary) as f:
    df = yaml.full_load(f)

if not 'active' in df.keys():
    df['active'] = ''
elif not 'mediopassive' in df.keys():
    df['mediopassive'] = ''

with open(template) as f:
    liq = Liquid(f)

ret = liq.render(word = df)
print(ret)
Beispiel #25
0
    args = parser.parse_args()

# read csv
csv_df = pandas.read_csv(args.csv)
csv_df.fillna("", inplace=True)  #fill empty cells with ""
csv_dict = csv_df.to_dict(orient='records')

# read templates
liq_meta = Liquid(args.metadata, liquid_from_file=True)
liq_local = Liquid(args.local_image, liquid_from_file=True)
liq_remote = Liquid(args.remote_image, liquid_from_file=True)

# for each record
for i in range(0, len(csv_dict)):
    row = csv_dict[i]
    metadata = liq_meta.render(**row)
    metadata = metadata.replace("{_", "{{")
    metadata = metadata.replace("_}", "}}")

    local_filename = liq_local.render(**row)
    remote_filename = liq_remote.render(**row)

    print(local_filename, "---->", remote_filename)

    if args.verbose > 1:
        print(metadata)

    if args.action == 'upload':
        response = upload(local_filename, remote_filename, metadata)
        # if args.verbose>1 or response.status_code!=200: -->> status_code altijd 200 ook bij error
        print(json.dumps(response.json(), indent=4, sort_keys=True))
Beispiel #26
0
def render_from_file(template_file, variables):
    """Render from template string with interpolated variables."""
    template = Liquid(str(template_file))
    return template.render(**variables)
Beispiel #27
0
def test_include_relative(set_default_jekyll):
    liq = Liquid(TPLDIR / "parent.tpl", from_file=True)
    assert liq.render().strip() == "sub"

    liq = Liquid(f'{{% include_relative "{TPLDIR}/parent.tpl" %}}', )
    assert liq.render().strip() == "sub"
Beispiel #28
0
def test_else_no_if_state():
    liq = Liquid("{% if False %}{%else%}1{%endif%}")
    assert liq.render() == '1'
    liq = Liquid("{% if False %}{%elseif true%}1{%endif%}")
    assert liq.render() == '1'
Beispiel #29
0
if not ARGS.dry_run:
    # Download the cover image so I don't hit their API to hard.
    with open("static/images/cover.jpg", "wb") as _fh:
        response = requests.get(_cover, stream=True)
        if not response.ok:
            print(response)
        for block in response.iter_content(1024):
            if not block:
                break
            _fh.write(block)

# The title
_title = currently_reading.h3.a.text
if LOG:
    print("Title:", _title)

# The author
_author = currently_reading.find("span", class_="bookauthor").a.text
if LOG:
    print("Author:", _author)

liq = Liquid("static/README-template.md")
ret = liq.render(book_name=_title, book_author=_author, book_url=_book_url)

if ARGS.dry_run:
    print(ret)
else:
    with open("README.md", "w") as _fh:
        _fh.write(ret)
Beispiel #30
0
def test_issue9(HERE, debug):
    liq = Liquid(
        '{%% assign foo = "test" %%}{%% include %s/templates/include_issue9.liq %%}'
        % HERE,
        liquid_loglevel='debug')
    assert liq.render() == 'test\nAccented character "ì" for testing\ntest'