How to get variables along with their filter name from JINJA2 templateHow to randomly select an item from a list?How to get the current time in PythonGetting the class name of an instance?How do I pass a variable by reference?How do you read from stdin?Get lengths of a list in a jinja2 templateHow do I get the number of elements in a list in Python?How to access environment variable values?How to remove a key from a Python dictionary?Delete column from pandas DataFrame by column name

How can I support myself financially as a 17 year old with a loan?

Are we obligated to aspire to be Talmidei Chachamim?

Is it cheaper to drop cargo than to land it?

Manager is threatning to grade me poorly if I don't complete the project

Why wasn't the Night King naked in S08E03?

Does this article imply that Turing-Computability is not the same as "effectively computable"?

Why do money exchangers give different rates to different bills?

Which industry am I working in? Software development or financial services?

I may be a fraud

Are triangulations of compact manifolds PL homeomorphic?

Theorem won't go to multiple lines and is causing text to run off the page

Reconstruct a matrix from its traces

What word means "to make something obsolete"?

What was the state of the German rail system in 1944?

To customize a predefined symbol with different colors

If Earth is tilted, why is Polaris always above the same spot?

Besides the up and down quark, what other quarks are present in daily matter around us?

Where can I go to avoid planes overhead?

A non-technological, repeating, phenomenon in the sky, holding its position in the sky for hours

For a benzene shown in a skeletal structure, what does a substituent to the center of the ring mean?

FindInstance and cosine system of equations

LightGBM results differently depending on the order of the data

Why was the battle set up *outside* Winterfell?

Is a lifestealing melee cantrip, in the form of booming blade, unbalanced?



How to get variables along with their filter name from JINJA2 template


How to randomly select an item from a list?How to get the current time in PythonGetting the class name of an instance?How do I pass a variable by reference?How do you read from stdin?Get lengths of a list in a jinja2 templateHow do I get the number of elements in a list in Python?How to access environment variable values?How to remove a key from a Python dictionary?Delete column from pandas DataFrame by column name






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








2















I am working on a GAE (python) and JINJA based application. I have created a JINJA template from a text string using from_string method. i.e.



template = JINJA.from_string(text)


The result template looks like this:



Template(body=[Scope(body=[ScopedEvalContextModifier(options=[Keyword(key='autoescape', value=Name(name='on', ctx='load'))], body=[Output(nodes=[TemplateData(data=u'Dear '), Filter(node=Name(name='customer_name', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u',nn'), Filter(node=Name(name='customer_name_new', ctx='load'), name='extra', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n nThank you for choosing '), Name(name='company_name', ctx='load'), TemplateData(data=u'.nn')]), If(test=Name(name='start_datetime', ctx='load'), body=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is scheduled for:n'), Filter(node=Name(name='start_datetime_block', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'nYou can check out the estimated time of arrival for your '), Name(name='order_type', ctx='load'), TemplateData(data=u' using the button belown'), Filter(node=Name(name='live_link_button', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is now placed.n')])]), If(test=And(left=Name(name='start_datetime', ctx='load'), right=Name(name='confirmation_required', ctx='load')), body=[Output(nodes=[TemplateData(data=u'Please confirm your availability for this appointment:n'), Filter(node=Name(name='confirmation_buttons', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), If(test=Name(name='custom_text', ctx='load'), body=[Output(nodes=[Filter(node=Name(name='custom_text', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), Output(nodes=[TemplateData(data=u'We look forward to seeing you. In case you have any questions please reach us at '), Name(name='company_email', ctx='load'), TemplateData(data=u'. '), Name(name='company_name', ctx='load'), TemplateData(data=u' '), Name(name='company_address', ctx='load'), TemplateData(data=u' '), Name(name='company_phone', ctx='load')])])])])


Now, what I want to do is that I want to get all the variables from this template and especially I am concerned with such variables which have some filters like in above template expected filters are safe and extra. Please note that extra is my custom filter.



Calling meta.find_undeclared_variables method only gives me list of keywords but, not their filters. i.e.



parsed_content = JINJA.parse(text)
keywords = meta.find_undeclared_variables(parsed_content)


Is there any way I can get keywords along with filter names as well?










share|improve this question




























    2















    I am working on a GAE (python) and JINJA based application. I have created a JINJA template from a text string using from_string method. i.e.



    template = JINJA.from_string(text)


    The result template looks like this:



    Template(body=[Scope(body=[ScopedEvalContextModifier(options=[Keyword(key='autoescape', value=Name(name='on', ctx='load'))], body=[Output(nodes=[TemplateData(data=u'Dear '), Filter(node=Name(name='customer_name', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u',nn'), Filter(node=Name(name='customer_name_new', ctx='load'), name='extra', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n nThank you for choosing '), Name(name='company_name', ctx='load'), TemplateData(data=u'.nn')]), If(test=Name(name='start_datetime', ctx='load'), body=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is scheduled for:n'), Filter(node=Name(name='start_datetime_block', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'nYou can check out the estimated time of arrival for your '), Name(name='order_type', ctx='load'), TemplateData(data=u' using the button belown'), Filter(node=Name(name='live_link_button', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is now placed.n')])]), If(test=And(left=Name(name='start_datetime', ctx='load'), right=Name(name='confirmation_required', ctx='load')), body=[Output(nodes=[TemplateData(data=u'Please confirm your availability for this appointment:n'), Filter(node=Name(name='confirmation_buttons', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), If(test=Name(name='custom_text', ctx='load'), body=[Output(nodes=[Filter(node=Name(name='custom_text', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), Output(nodes=[TemplateData(data=u'We look forward to seeing you. In case you have any questions please reach us at '), Name(name='company_email', ctx='load'), TemplateData(data=u'. '), Name(name='company_name', ctx='load'), TemplateData(data=u' '), Name(name='company_address', ctx='load'), TemplateData(data=u' '), Name(name='company_phone', ctx='load')])])])])


    Now, what I want to do is that I want to get all the variables from this template and especially I am concerned with such variables which have some filters like in above template expected filters are safe and extra. Please note that extra is my custom filter.



    Calling meta.find_undeclared_variables method only gives me list of keywords but, not their filters. i.e.



    parsed_content = JINJA.parse(text)
    keywords = meta.find_undeclared_variables(parsed_content)


    Is there any way I can get keywords along with filter names as well?










    share|improve this question
























      2












      2








      2








      I am working on a GAE (python) and JINJA based application. I have created a JINJA template from a text string using from_string method. i.e.



      template = JINJA.from_string(text)


      The result template looks like this:



      Template(body=[Scope(body=[ScopedEvalContextModifier(options=[Keyword(key='autoescape', value=Name(name='on', ctx='load'))], body=[Output(nodes=[TemplateData(data=u'Dear '), Filter(node=Name(name='customer_name', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u',nn'), Filter(node=Name(name='customer_name_new', ctx='load'), name='extra', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n nThank you for choosing '), Name(name='company_name', ctx='load'), TemplateData(data=u'.nn')]), If(test=Name(name='start_datetime', ctx='load'), body=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is scheduled for:n'), Filter(node=Name(name='start_datetime_block', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'nYou can check out the estimated time of arrival for your '), Name(name='order_type', ctx='load'), TemplateData(data=u' using the button belown'), Filter(node=Name(name='live_link_button', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is now placed.n')])]), If(test=And(left=Name(name='start_datetime', ctx='load'), right=Name(name='confirmation_required', ctx='load')), body=[Output(nodes=[TemplateData(data=u'Please confirm your availability for this appointment:n'), Filter(node=Name(name='confirmation_buttons', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), If(test=Name(name='custom_text', ctx='load'), body=[Output(nodes=[Filter(node=Name(name='custom_text', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), Output(nodes=[TemplateData(data=u'We look forward to seeing you. In case you have any questions please reach us at '), Name(name='company_email', ctx='load'), TemplateData(data=u'. '), Name(name='company_name', ctx='load'), TemplateData(data=u' '), Name(name='company_address', ctx='load'), TemplateData(data=u' '), Name(name='company_phone', ctx='load')])])])])


      Now, what I want to do is that I want to get all the variables from this template and especially I am concerned with such variables which have some filters like in above template expected filters are safe and extra. Please note that extra is my custom filter.



      Calling meta.find_undeclared_variables method only gives me list of keywords but, not their filters. i.e.



      parsed_content = JINJA.parse(text)
      keywords = meta.find_undeclared_variables(parsed_content)


      Is there any way I can get keywords along with filter names as well?










      share|improve this question














      I am working on a GAE (python) and JINJA based application. I have created a JINJA template from a text string using from_string method. i.e.



      template = JINJA.from_string(text)


      The result template looks like this:



      Template(body=[Scope(body=[ScopedEvalContextModifier(options=[Keyword(key='autoescape', value=Name(name='on', ctx='load'))], body=[Output(nodes=[TemplateData(data=u'Dear '), Filter(node=Name(name='customer_name', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u',nn'), Filter(node=Name(name='customer_name_new', ctx='load'), name='extra', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n nThank you for choosing '), Name(name='company_name', ctx='load'), TemplateData(data=u'.nn')]), If(test=Name(name='start_datetime', ctx='load'), body=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is scheduled for:n'), Filter(node=Name(name='start_datetime_block', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'nYou can check out the estimated time of arrival for your '), Name(name='order_type', ctx='load'), TemplateData(data=u' using the button belown'), Filter(node=Name(name='live_link_button', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[Output(nodes=[TemplateData(data=u'Your '), Name(name='order_type', ctx='load'), TemplateData(data=u' is now placed.n')])]), If(test=And(left=Name(name='start_datetime', ctx='load'), right=Name(name='confirmation_required', ctx='load')), body=[Output(nodes=[TemplateData(data=u'Please confirm your availability for this appointment:n'), Filter(node=Name(name='confirmation_buttons', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), If(test=Name(name='custom_text', ctx='load'), body=[Output(nodes=[Filter(node=Name(name='custom_text', ctx='load'), name='safe', args=[], kwargs=[], dyn_args=None, dyn_kwargs=None), TemplateData(data=u'n')])], else_=[]), Output(nodes=[TemplateData(data=u'We look forward to seeing you. In case you have any questions please reach us at '), Name(name='company_email', ctx='load'), TemplateData(data=u'. '), Name(name='company_name', ctx='load'), TemplateData(data=u' '), Name(name='company_address', ctx='load'), TemplateData(data=u' '), Name(name='company_phone', ctx='load')])])])])


      Now, what I want to do is that I want to get all the variables from this template and especially I am concerned with such variables which have some filters like in above template expected filters are safe and extra. Please note that extra is my custom filter.



      Calling meta.find_undeclared_variables method only gives me list of keywords but, not their filters. i.e.



      parsed_content = JINJA.parse(text)
      keywords = meta.find_undeclared_variables(parsed_content)


      Is there any way I can get keywords along with filter names as well?







      python django flask jinja2






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 7:14









      HamidArrivyHamidArrivy

      68210




      68210






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Here is a simple solution that might help. It gives variable name with filters (only variables that have filters):



          from jinja2 import Environment, PackageLoader, meta, nodes

          def find_filters(ast):
          """Find all the nodes of a given type. If the type is a tuple,
          the check is performed for any of the tuple items.
          """
          for child in ast.iter_child_nodes():
          if isinstance(child, nodes.Filter):
          yield child
          else:
          for result in find_filters(child):
          yield result


          def filtered_variables(ast):
          """Return variables that have filters, along with their filters. might
          return duplicate variable names with different filters
          """
          results = []
          for i, node in enumerate(find_filters(ast)):
          filters = []
          f = node
          filters.append(f.name)
          while isinstance(f.node, nodes.Filter):
          f = f.node
          filters.append(f.name)
          filters.reverse()
          results.append((f.node.name, filters))
          return results


          env = Environment(loader=PackageLoader('templates'))

          template = '% extends "layout.html" %'
          '% from "test.html" import a, b as c % x some_other '
          '% import "meh.html" as meh % some_variable '
          '% include "muh.html" %'

          ast = env.parse(template)
          print(filtered_variables(ast))


          The output will be:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd'])]


          You can include variables that has no filter like this:



          f_vars = filtered_variables(ast)
          filtered = []
          for var in f_vars:
          filtered.append(var[0])
          f = [(x, []) for x in keywords if x not in filtered]
          f_vars.extend(f)
          print(f_vars)


          Output:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd']), ('some_other', [])]


          Note that result might have duplicate values. This can be more useful as different filters might be present on each occurrence of variable.






          share|improve this answer

























          • Thanks a lot! Exactly what I was looking for.

            – HamidArrivy
            Mar 25 at 8:02











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55275399%2fhow-to-get-variables-along-with-their-filter-name-from-jinja2-template%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Here is a simple solution that might help. It gives variable name with filters (only variables that have filters):



          from jinja2 import Environment, PackageLoader, meta, nodes

          def find_filters(ast):
          """Find all the nodes of a given type. If the type is a tuple,
          the check is performed for any of the tuple items.
          """
          for child in ast.iter_child_nodes():
          if isinstance(child, nodes.Filter):
          yield child
          else:
          for result in find_filters(child):
          yield result


          def filtered_variables(ast):
          """Return variables that have filters, along with their filters. might
          return duplicate variable names with different filters
          """
          results = []
          for i, node in enumerate(find_filters(ast)):
          filters = []
          f = node
          filters.append(f.name)
          while isinstance(f.node, nodes.Filter):
          f = f.node
          filters.append(f.name)
          filters.reverse()
          results.append((f.node.name, filters))
          return results


          env = Environment(loader=PackageLoader('templates'))

          template = '% extends "layout.html" %'
          '% from "test.html" import a, b as c % x some_other '
          '% import "meh.html" as meh % some_variable '
          '% include "muh.html" %'

          ast = env.parse(template)
          print(filtered_variables(ast))


          The output will be:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd'])]


          You can include variables that has no filter like this:



          f_vars = filtered_variables(ast)
          filtered = []
          for var in f_vars:
          filtered.append(var[0])
          f = [(x, []) for x in keywords if x not in filtered]
          f_vars.extend(f)
          print(f_vars)


          Output:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd']), ('some_other', [])]


          Note that result might have duplicate values. This can be more useful as different filters might be present on each occurrence of variable.






          share|improve this answer

























          • Thanks a lot! Exactly what I was looking for.

            – HamidArrivy
            Mar 25 at 8:02















          1














          Here is a simple solution that might help. It gives variable name with filters (only variables that have filters):



          from jinja2 import Environment, PackageLoader, meta, nodes

          def find_filters(ast):
          """Find all the nodes of a given type. If the type is a tuple,
          the check is performed for any of the tuple items.
          """
          for child in ast.iter_child_nodes():
          if isinstance(child, nodes.Filter):
          yield child
          else:
          for result in find_filters(child):
          yield result


          def filtered_variables(ast):
          """Return variables that have filters, along with their filters. might
          return duplicate variable names with different filters
          """
          results = []
          for i, node in enumerate(find_filters(ast)):
          filters = []
          f = node
          filters.append(f.name)
          while isinstance(f.node, nodes.Filter):
          f = f.node
          filters.append(f.name)
          filters.reverse()
          results.append((f.node.name, filters))
          return results


          env = Environment(loader=PackageLoader('templates'))

          template = '% extends "layout.html" %'
          '% from "test.html" import a, b as c % x some_other '
          '% import "meh.html" as meh % some_variable '
          '% include "muh.html" %'

          ast = env.parse(template)
          print(filtered_variables(ast))


          The output will be:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd'])]


          You can include variables that has no filter like this:



          f_vars = filtered_variables(ast)
          filtered = []
          for var in f_vars:
          filtered.append(var[0])
          f = [(x, []) for x in keywords if x not in filtered]
          f_vars.extend(f)
          print(f_vars)


          Output:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd']), ('some_other', [])]


          Note that result might have duplicate values. This can be more useful as different filters might be present on each occurrence of variable.






          share|improve this answer

























          • Thanks a lot! Exactly what I was looking for.

            – HamidArrivy
            Mar 25 at 8:02













          1












          1








          1







          Here is a simple solution that might help. It gives variable name with filters (only variables that have filters):



          from jinja2 import Environment, PackageLoader, meta, nodes

          def find_filters(ast):
          """Find all the nodes of a given type. If the type is a tuple,
          the check is performed for any of the tuple items.
          """
          for child in ast.iter_child_nodes():
          if isinstance(child, nodes.Filter):
          yield child
          else:
          for result in find_filters(child):
          yield result


          def filtered_variables(ast):
          """Return variables that have filters, along with their filters. might
          return duplicate variable names with different filters
          """
          results = []
          for i, node in enumerate(find_filters(ast)):
          filters = []
          f = node
          filters.append(f.name)
          while isinstance(f.node, nodes.Filter):
          f = f.node
          filters.append(f.name)
          filters.reverse()
          results.append((f.node.name, filters))
          return results


          env = Environment(loader=PackageLoader('templates'))

          template = '% extends "layout.html" %'
          '% from "test.html" import a, b as c % x some_other '
          '% import "meh.html" as meh % some_variable '
          '% include "muh.html" %'

          ast = env.parse(template)
          print(filtered_variables(ast))


          The output will be:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd'])]


          You can include variables that has no filter like this:



          f_vars = filtered_variables(ast)
          filtered = []
          for var in f_vars:
          filtered.append(var[0])
          f = [(x, []) for x in keywords if x not in filtered]
          f_vars.extend(f)
          print(f_vars)


          Output:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd']), ('some_other', [])]


          Note that result might have duplicate values. This can be more useful as different filters might be present on each occurrence of variable.






          share|improve this answer















          Here is a simple solution that might help. It gives variable name with filters (only variables that have filters):



          from jinja2 import Environment, PackageLoader, meta, nodes

          def find_filters(ast):
          """Find all the nodes of a given type. If the type is a tuple,
          the check is performed for any of the tuple items.
          """
          for child in ast.iter_child_nodes():
          if isinstance(child, nodes.Filter):
          yield child
          else:
          for result in find_filters(child):
          yield result


          def filtered_variables(ast):
          """Return variables that have filters, along with their filters. might
          return duplicate variable names with different filters
          """
          results = []
          for i, node in enumerate(find_filters(ast)):
          filters = []
          f = node
          filters.append(f.name)
          while isinstance(f.node, nodes.Filter):
          f = f.node
          filters.append(f.name)
          filters.reverse()
          results.append((f.node.name, filters))
          return results


          env = Environment(loader=PackageLoader('templates'))

          template = '% extends "layout.html" %'
          '% from "test.html" import a, b as c % x some_other '
          '% import "meh.html" as meh % some_variable '
          '% include "muh.html" %'

          ast = env.parse(template)
          print(filtered_variables(ast))


          The output will be:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd'])]


          You can include variables that has no filter like this:



          f_vars = filtered_variables(ast)
          filtered = []
          for var in f_vars:
          filtered.append(var[0])
          f = [(x, []) for x in keywords if x not in filtered]
          f_vars.extend(f)
          print(f_vars)


          Output:



          [('some_variable', ['a', 'x']), ('some_variable', ['b', 'c', 'd']), ('some_other', [])]


          Note that result might have duplicate values. This can be more useful as different filters might be present on each occurrence of variable.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 30 at 19:56

























          answered Mar 22 at 21:04









          maanijoumaanijou

          670619




          670619












          • Thanks a lot! Exactly what I was looking for.

            – HamidArrivy
            Mar 25 at 8:02

















          • Thanks a lot! Exactly what I was looking for.

            – HamidArrivy
            Mar 25 at 8:02
















          Thanks a lot! Exactly what I was looking for.

          – HamidArrivy
          Mar 25 at 8:02





          Thanks a lot! Exactly what I was looking for.

          – HamidArrivy
          Mar 25 at 8:02



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55275399%2fhow-to-get-variables-along-with-their-filter-name-from-jinja2-template%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해