Example #1
0
def render(context, form='form'):
    '''
    Renders the form by the given name within the context.

    The primary advantage to using this tag (instead of simply ${ form }) is
    you can place additional html content within the tag, which prints
    at the bottom of the form.

    The `form` parameter can be a form object or form name (str) within the context.

    # Use the context variable "form".
        <%namespace name="fl" module="formlib.tags"/>
        <%fl:render/>

    # Form by name (context key):
        <%namespace name="fl" module="formlib.tags"/>
        <%fl:render form='form_key'/>

    # Direct reference to form object:
        <%namespace name="fl" module="formlib.tags"/>
        <%fl:render form='${ form_obj }'/>
    '''
    formobj = form
    if isinstance(form, str):
        formobj = context.get(form)
        if formobj is None:
            raise ValueError('Context key `{}` not found'.format(form))
    if not isinstance(formobj, Formless):
        raise ValueError(
            'Object {} is not a Formless subclass'.format(formobj))

    extra = capture(context, context['caller'].body)
    return formobj.as_full(extra=extra)
Example #2
0
 def generate_page():
     c.timer.from_cache = False
     do_work(key)
     return zlib.compress(
         capture(context, mako_def.body).encode('utf8'),
         1
     )
Example #3
0
def kernel(context, name, ndim, **kwargs):
    extrns = context['_extrns']

    # Validate the argument list
    if any(arg in extrns for arg in kwargs):
        raise ValueError('Duplicate argument in {0}: {1} {2}'.format(
            name, list(kwargs), list(extrns)))

    # Merge local and external arguments
    kwargs = dict(kwargs, **extrns)

    # Capture the kernel body
    body = capture(context, context['caller'].body)

    # Get the generator class and floating point data type
    kerngen, fpdtype = context['_kernel_generator'], context['fpdtype']

    # Instantiate
    kern = kerngen(name, int(ndim), kwargs, body, fpdtype)

    # Save the argument/type list for later use
    context['_kernel_argspecs'][name] = kern.argspec()

    # Render and return the complete kernel
    return kern.render()
Example #4
0
def indent(context, level=1, **kwargs):
    spaces = int(level) * 4
    lines = capture(context, context['caller'].body).splitlines(True)
    output = []
    for line in lines:
        output.append((' ' * spaces) + line.strip())
    return '\n'.join(output)
Example #5
0
def function(context, name, params, rett='void'):
    # Capture the function body
    body = capture(context, context['caller'].body)

    # Get the generator class and floating point data type
    funcgen, fpdtype = context['_function_generator'], context['fpdtype']

    # Render the complete function
    return funcgen(name, params, rett, body, fpdtype).render()
Example #6
0
 def decorate(context, *args, **kwargs):
     css_block = capture(context, fn, *args, **kwargs).strip()
     if context['compress']:
         try:
             css_block = compress_css(css_block, context)
         except Exception as err_:
             print(traceback.format_exc())
             raise
     context.write(css_block)
     return
Example #7
0
def kernel(context, name, ndim, **kwargs):
    # Capture the kernel body
    body = capture(context, context['caller'].body)

    # Get the generator class and floating point data type
    kerngen, fpdtype = context['_kernel_generator'], context['fpdtype']

    # Instantiate
    kern = kerngen(name, int(ndim), kwargs, body, fpdtype)

    # Save the argument/type list for later use
    context['_kernel_argspecs'][name] = kern.argspec()

    # Render and return the complete kernel
    return kern.render()
Example #8
0
def kernel(context, name, ndim, **kwargs):
    # Capture the kernel body
    body = capture(context, context['caller'].body)

    # Get the generator class and floating point data type
    kerngen, fpdtype = context['_kernel_generator'], context['fpdtype']

    # Instantiate
    kern = kerngen(name, int(ndim), kwargs, body, fpdtype)

    # Save the argument/type list for later use
    context['_kernel_argspecs'][name] = kern.argspec()

    # Render and return the complete kernel
    return kern.render()
Example #9
0
def macro(context, name, params):
    # Check we have not already been defined
    if name in context['_macros']:
        raise RuntimeError('Attempt to redefine macro "{0}"'.format(name))

    # Split up the parameter list
    params = [p.strip() for p in params.split(',')]

    # Capture the function body
    body = capture(context, context['caller'].body)

    # Identify any local variable declarations
    lvars = _locals(body)

    # Suffix these variables by a '_'
    if lvars:
        body = re.sub(r'\b({0})\b'.format('|'.join(lvars)), r'\1_', body)

    # Save
    context['_macros'][name] = (params, body)

    return ''
Example #10
0
def macro(context, name, params):
    # Check we have not already been defined
    if name in context['_macros']:
        raise RuntimeError('Attempt to redefine macro "{0}"'
                           .format(name))

    # Split up the parameter list
    params = [p.strip() for p in params.split(',')]

    # Capture the function body
    body = capture(context, context['caller'].body)

    # Identify any local variable declarations
    lvars = _locals(body)

    # Suffix these variables by a '_'
    if lvars:
        body = re.sub(r'\b({0})\b'.format('|'.join(lvars)), r'\1_', body)

    # Save
    context['_macros'][name] = (params, body)

    return ''
Example #11
0
def tabify(context, separators="", **kwargs):
    lines = capture(context, context['caller'].body).splitlines(True)
    for sep in separators:
        true_sep = ' ' + sep if sep != ' ' else sep
        # Break every line into sections based on this separator
        line_parts = [x.split(true_sep) for x in lines]
        max_widths = []
        for parts in line_parts:
            for i in range(len(parts)):
                if i >= len(max_widths):
                    max_widths.append(len(parts[i]))
                elif len(parts[i]) > max_widths[i]:
                    max_widths[i] = len(parts[i])
        # Pad out each section of each line to match the maximum width
        lines = []
        for parts in line_parts:
            result = ""
            for i in range(len(parts) - 1):
                padding = ' ' * (max_widths[i] - len(parts[i]))
                result += f"{parts[i]}{padding} {sep}"
            result += parts[-1]
            lines.append(result)
    return ''.join(lines)
Example #12
0
 def decorate(context, *args, **kwargs):
     css_block = capture(context, fn, *args, **kwargs).strip()
     context.write(cssmin(css_block))
Example #13
0
 def generate_page():
     c.timer.from_cache = False
     do_work(key)
     return zlib.compress(
         capture(context, mako_def.body).encode('utf8'), 1)