0

I am trying make a macro that takes in arguments and adds the elements to the form field. This is my current code.

      {% macro render_field(field,class,**custom) %}
  <div class="form-group">
    {% if field.name != "submit" %}
    {{ field.label }}
    {% endif %}



      {{ field(class="form-control %s" % class , custom ) }}
  </div>
  {% endmacro %}


{{ render_field(form.reciver_name,"test","placeholder = a") }}

I just dont know how to accept multiple arguments and dont understand **kwargs very well

I get this error TemplateSyntaxError: expected token 'name', got '**'

David Gonzalez
  • 135
  • 3
  • 14
  • What problem are you encountering with your code? Can you provide an example of what you expect to happen? – alexbclay Sep 12 '16 at 01:15
  • So when i do do this {{ render_field(form.reciver_name,"test","placeholder = a") }} I want it to output – David Gonzalez Sep 12 '16 at 02:01
  • You may have a problem using a reserved keyword, in this case `class`, as the name of an argument. WTForms handles this through an argument named `class_`. Try using that instead. – dirn Sep 12 '16 at 02:05
  • that is not where the problem is. I dont think that is the case but i changed the parameter name just in case – David Gonzalez Sep 12 '16 at 02:12

1 Answers1

2

Jinja macros aren't exactly the same as defining a python function. See here: http://jinja.pocoo.org/docs/dev/templates/#macros

So I don't think you need the **custom in your macro definition. Also, when you are calling the macro, the third argument is not a keyword argument. It is the literal string "placeholder = a".

You can try call the macro like this:

{{ render_field(form.reciver_name, "test", placeholder="a") }}

Jinja should put the placeholder keyword arg in the kwargs special variable. I'm not very familiar with flask-wtforms, but you should be able to use this kwargs variable in the field(...) function call.

For future reference: kwargs needs to be accessed at least once in the macro for it to accept any keyword arguments. See linked duplicate question for more details.

alexbclay
  • 1,389
  • 14
  • 19
  • When I try this "TypeError: macro 'render_field' takes no keyword argument 'placeholder'" but thankyou for the tip of kwargs as a special variable – David Gonzalez Sep 12 '16 at 02:27
  • You need to actually use `**kwargs` in the `render_field` call. Jinja macros automagically accept arbitrary kwargs if you use `kwargs` inside the macro. See http://jinja.pocoo.org/docs/dev/templates/#macros – ThiefMaster Sep 12 '16 at 11:46