|
12 | 12 | from . import NURBS, compatibility
|
13 | 13 |
|
14 | 14 |
|
| 15 | +def process_template(file_src): |
| 16 | + """ Process Jinja2 template input |
| 17 | +
|
| 18 | + :param file_src: file contents |
| 19 | + :type file_src: str |
| 20 | + """ |
| 21 | + def t_sqrt(val): |
| 22 | + """ Square-root of the input value """ |
| 23 | + return math.sqrt(val) |
| 24 | + |
| 25 | + def t_cubert(val): |
| 26 | + """ Cube-root of the input value """ |
| 27 | + return val**(1.0 / 3.0) if val >= 0 else -(-val)**(1.0 / 3.0) |
| 28 | + |
| 29 | + def t_pow(val, pow): |
| 30 | + """ 'val' to the power 'pow' """ |
| 31 | + return math.pow(val, pow) |
| 32 | + |
| 33 | + # Check if it is possible to import 'jinja2' |
| 34 | + try: |
| 35 | + import jinja2 |
| 36 | + except ImportError: |
| 37 | + print("Please install 'jinja2' package to use templated input: pip install jinja2") |
| 38 | + return |
| 39 | + |
| 40 | + # Replace jinja2 template tags for compatibility |
| 41 | + fsrc = file_src.replace("{%", "<%").replace("%}", "%>").replace("{{", "<{").replace("}}", "}>") |
| 42 | + |
| 43 | + # Generate Jinja2 environment |
| 44 | + env = jinja2.Environment( |
| 45 | + loader=jinja2.BaseLoader(), |
| 46 | + trim_blocks=True, |
| 47 | + block_start_string='<%', block_end_string='%>', |
| 48 | + variable_start_string='<{', variable_end_string='}>' |
| 49 | + ).from_string(fsrc) |
| 50 | + |
| 51 | + # Load custom functions into the Jinja2 environment |
| 52 | + template_funcs = dict( |
| 53 | + sqrt=t_sqrt, |
| 54 | + cubert=t_cubert, |
| 55 | + pow=t_pow, |
| 56 | + ) |
| 57 | + for k, v in template_funcs.items(): |
| 58 | + env.globals[k] = v |
| 59 | + |
| 60 | + # Process Jinja2 template functions & variables inside the input file |
| 61 | + return env.render() |
| 62 | + |
| 63 | + |
15 | 64 | def read_file(file_name, **kwargs):
|
16 | 65 | binary = kwargs.get('binary', False)
|
17 | 66 | skip_lines = kwargs.get('skip_lines', 0)
|
|
0 commit comments