1

Hi i am trying to create a function which allow string input as below:

def change_template(condition):
    template='''
             <div style="background:<%= 
             (function colorfromint(){
              if(condition){ #change the condition inside here
              return("green")}
                }()) %>; 
            color: black"> 
        <%= value %>
        </div>
        '''
    return template

So whenever I input condition into change_template function, let say change_template('A' < 'B') then the condition would be

template='''
          <div style="background:<%= 
          (function colorfromint(){
          if('A' < 'B'){ #change the condition inside here
          return("green")}
          }()) %>; 
          color: black"> 
          <%= value %>
          </div>
            '''
5
  • 1
    Can you please explain the problem that you are facing? Commented May 15, 2020 at 4:01
  • Do you perhaps mean "'A' < 'B'"? Commented May 15, 2020 at 4:05
  • Okay, so the question is how to modify the "template" string so as to insert the content from condition? Or just what exactly? Commented May 15, 2020 at 4:07
  • @KarlKnechtel yup to modify the template based on the content from condition Commented May 15, 2020 at 4:11
  • Maybe try adding your html into 1 line join the strings either side of condition like '<div>...' + condition + '...</div>' Commented May 15, 2020 at 4:11

2 Answers 2

2

You can do this to set your condition inside your template, or you can use format like what @Daniel said.

def change_template(condition):
  template='''
        <div style="background:<%= 
        (function colorfromint(){
        if('''+condition+'''){ #change the condition inside here
        return("green")}
          }()) %>; 
      color: black"> 
  <%= value %>
  </div>
  '''
  return template

print(change_template("'A'<'B'"))

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the format method for strings. Here's an example.

x='hello'
y='foo {} bar'.format(x)
print(y)

This produces

foo hello bar

EDIT:

If your Python version is at least 3.6, you could also use f-strings. E.g.,

x='hello'
y=f'foo {x} bar'
print(y)

Same output.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.