I would like to add a value attribute to multiple input elements. Currently, I am simply using a replace which works but is cumbersome. Is there a way to find an element by its ID attribute and simply add a value attribute?
page = render_template('template.html')
page = page.replace('<input type="text" id="Company" name="Company" placeholder="Company name" data-bs-toggle="tooltip" title="The name of the company that the document is for." onblur="titleCase(this)">',
'<input type="text" id="Company" name="Company" placeholder="Company name" data-bs-toggle="tooltip" title="The name of the company that the document is for." onblur="titleCase(this)" value="' company '">')
Is there a way to do this without overcomplicating things?
EDIT: I found this an example in lxml.html documentation that encouraged me to do this:
def fillForm1(page, pDate, company, manager, cAddress, cPhone, cEmail ,sAddress):
form_page = fromstring(page)
form = form_page.forms[0]
form.fields = dict(
pDate=pDate,
Company=company,
Manager=manager,
cAddress=cAddress,
cPhone=cPhone,
cEmail=cEmail,
sAddress=sAddress
)
page = page.replace('<form method="post">', tostring(form, pretty_print=True, encoding='UTF-8', with_tail=False,))
return page
But I keep getting an error about passing a byte back when it should be a string.
CodePudding user response:
Since You are using render_template
you can simply use Jinja
Jinja helps you to render your data where ever you want in the html page safely and no need to install anything since the the render_template
method already uses it.
You need to specify a something like a placeholder in your html file and then pass a value to it as a keyword to the render_template
you need to put this in your HTML file
<input value="{{company}}" type="text" id="Company" name="Company" placeholder="Company name" data-bs-toggle="tooltip" title="The name of the company that the document is for." onblur="titleCase(this)" >
Now Jinja will search for a keyword (from what you've passed) named company and will substitute its value in place pf
{{company}}
to pass the value to Jinja simply use this line in your python code
company_value = "Some Value"
page = render_template('template.html', company=company_value)
Now When Jinja see {{company}}
it will replace it with the value passed which is the value of company_value = "Some Value"
Note that you can pass as much values as you want
Jinja has more features that help you to render your data like:
- loops
- if else statements
- and a lot more
Check this Documentation for a quick look Jinja