def submit(self, value="Save changes", name=None, confirm=None, disable_with=None, **options): """Creates a submit button with the text ``value`` as the caption. Options: * ``confirm`` - A confirm message displayed when the button is clicked. * ``disable_with`` - The value to be used to rename a disabled version of the submit button. """ if confirm: onclick = options.get('onclick', '') if onclick.strip() and not onclick.rstrip().endswith(';'): onclick += ';' #options['onclick'] = "%sreturn %s;" % (onclick, confirm_javascript_function(confirm)) options['onclick'] = onclick if name: options['name_'] = name if disable_with: options["onclick"] = "this.disabled=true;this.value='%s';this.form.submit();%s" % (disable_with, options.get("onclick", '')) o = {'type': 'submit'} o.update(options) return HTML.input(value=value, **o)
def radio(name, value, checked=False, label=None, **attrs): """Create a radio button. Arguments: ``name`` -- the field's name. ``value`` -- the value returned to the application if the button is pressed. ``checked`` -- true if the button should be initially pressed. ``label`` -- a text label to display to the right of the button. The id of the radio button will be set to the name + '_' + value to ensure its uniqueness. An ``id`` keyword arg overrides this. (Note that this behavior is unique to the ``radio()`` helper.) To arrange multiple radio buttons in a group, see webhelpers.containers.distribute(). """ _set_input_attrs(attrs, "radio", name, value) if checked: attrs["checked"] = "checked" if not "id" in attrs: attrs["id"] = '%s_%s' % (name, _make_safe_id_component(value)) widget = HTML.input(**attrs) if label: widget = HTML.label(widget, label) return widget
def radio(name, value, checked=False, label=None, **attrs): """Create a radio button. Arguments: ``name`` -- the field's name. ``value`` -- the value returned to the application if the button is pressed. ``checked`` -- true if the button should be initially pressed. ``label`` -- a text label to display to the right of the button. The id of the radio button will be set to the name + '_' + value to ensure its uniqueness. An ``id`` keyword arg overrides this. (Note that this behavior is unique to the ``radio()`` helper.) To arrange multiple radio buttons in a group, see webhelpers.containers.distribute(). """ _set_input_attrs(attrs, "radio", name, value) if checked: attrs["checked"] = "checked" if not "id" in attrs: attrs["id"] = '%s_%s' % (name, _make_safe_id_component(value)) widget = HTML.input(**attrs) if label: widget = HTML.label(widget, label) return widget
def checkbox(name, value="1", checked=False, **attrs): """Create a check box. Options: * ``checked`` - If true, the checkbox will be initially checked. This may be specified as a positional argument. * ``disabled`` - If true, checkbox will be grayed out. * ``readonly`` - If true, the user will not be able to modify the checkbox. Example:: >>> checkbox("hi") literal(u'<input name="hi" type="checkbox" value="1" />') """ set_input_attrs(attrs, "checkbox", name, value) attrs["type"] = "checkbox" attrs["name"] = name attrs["value"] = value if checked: attrs["checked"] = "checked" convert_boolean_attrs(attrs, ["disabled", "readonly"]) return HTML.input(**attrs)
def text(name, value=None, id=None, **attrs): """Create a standard text field. ``value`` is a string, the content of the text field. ``id`` is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through ``_make_safe_id_component()``. Pass the empty string ("") to suppress the ID attribute entirely. Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. The remaining keyword args will be standard HTML attributes for the tag. """ _set_input_attrs(attrs, "text", name, value) _set_id_attr(attrs, id, name) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def text(name, value=None, id=None, **attrs): """Create a standard text field. ``value`` is a string, the content of the text field. ``id`` is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through ``_make_safe_id_component()``. Pass the empty string ("") to suppress the ID attribute entirely. Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. The remaining keyword args will be standard HTML attributes for the tag. """ _set_input_attrs(attrs, "text", name, value) _set_id_attr(attrs, id, name) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def submit(self, value="Save changes", name=None, confirm=None, disable_with=None, **options): """Creates a submit button with the text ``value`` as the caption. Options: * ``confirm`` - A confirm message displayed when the button is clicked. * ``disable_with`` - The value to be used to rename a disabled version of the submit button. """ if confirm: onclick = options.get('onclick', '') if onclick.strip() and not onclick.rstrip().endswith(';'): onclick += ';' #options['onclick'] = "%sreturn %s;" % (onclick, confirm_javascript_function(confirm)) options['onclick'] = onclick if name: options['name_'] = name if disable_with: options[ "onclick"] = "this.disabled=true;this.value='%s';this.form.submit();%s" % ( disable_with, options.get("onclick", '')) o = {'type': 'submit'} o.update(options) return HTML.input(value=value, **o)
def password(name, value=None, **attrs): """Create a password field. Takes the same options as text_field. """ set_input_attrs(attrs, "password", name, value) return HTML.input(**attrs)
def _reset(name, value=None, id=NotGiven, type="reset", **attrs): """ Reset button """ _set_input_attrs(attrs, type, name, value) _set_id_attr(attrs, id, name) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def _reset(name, value=None, id=NotGiven, type="reset", **attrs): """ Reset button """ _set_input_attrs(attrs, type, name, value) _set_id_attr(attrs, id, name) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def password(name, value=None, id=None, **attrs): """Create a password field. Takes the same options as ``text()``. """ _set_input_attrs(attrs, "password", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)
def password(name, value=None, id=NotGiven, **attrs): """Create a password field. Takes the same options as ``text()``. """ _set_input_attrs(attrs, "password", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)
def checkbox(label, name, checked=False, **kwargs): kwargs['type'] = 'checkbox' kwargs['name'] = name if checked: kwargs['checked'] = 'checked' kwargs.setdefault('id', name) return HTML.div(class_='formField checkbox', id='%s-field' % kwargs['id'], c=[HTML.label(for_=name, c=[ HTML.input(**kwargs), HTML.span(class_='labelText', c=[label]) ]), HTML.literal('<form:error name="%s" />' % name)])
def radio(name, value, checked=False, **attrs): """Create a radio button. The id of the radio button will be set to the name + ' ' + value to ensure its uniqueness. An ``id`` keyword arg overrides this. """ set_input_attrs(attrs, "radio", name, value) if checked: attrs["checked"] = "checked" if not "id" in attrs: attrs["id"] = '%s_%s' % (name, _make_safe_id_component(value)) return HTML.input(**attrs)
def file(name, value=None, **attrs): """Create a file upload field. If you are using file uploads then you will also need to set the multipart option for the form. Example:: >>> file('myfile') literal(u'<input name="myfile" type="file" />') """ set_input_attrs(attrs, "file", name, value) return HTML.input(**attrs)
def file(name, value=None, id=None, **attrs): """Create a file upload field. If you are using file uploads then you will also need to set the multipart option for the form. Example:: >>> file('myfile') literal(u'<input id="myfile" name="myfile" type="file" />') """ _set_input_attrs(attrs, "file", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)
def radio_button(self, name, value, checked=False, show_errors=True, **options): """Creates a radio button. The id of the radio button will be set to the name + value with a _ in between to ensure its uniqueness. """ pretty_tag_value = re.sub(r'\s', "_", '%s' % value) pretty_tag_value = re.sub(r'(?!-)\W', "", pretty_tag_value).lower() html_options = {'type': 'radio', 'name_': name, 'value': value} html_options.update(options) if checked: html_options["checked"] = "checked" ret = HTML.input(**html_options) if show_errors: self.get_error(name) return ret
def check_box(self, name, value='1', checked=None, label='', show_errors=True, **options): """ Creates a check box. """ o = {'type': 'checkbox', 'name_': name, 'value': value} o.update(options) if checked == None and name in self.defaults: checked = self.defaults[name] if checked: o['checked'] = 'checked' ret = HTML.input(**o) if label: ret += ' ' + label if show_errors: ret += self.get_error(name) return ret
def text(name, value=None, **attrs): """Create a standard text field. ``value`` is a string, the content of the text field. Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. The remaining keyword args will be standard HTML attributes for the tag. """ set_input_attrs(attrs, "text", name, value) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def input_line(name, title, value='', help_text=None, right_next=None, **kwargs): expl = None if help_text is not None: expl = HTML.span(class_='helpText', c=help_text) next = None if right_next is not None: next = HTML.span(class_='rightNext', c=right_next) kwargs.setdefault('id', name) kwargs.setdefault('type', 'text') return HTML.div(class_='formField', id='%s-field' % kwargs['id'], c=[HTML.label(for_=name, c=[ HTML.span(class_='labelText', c=[title]), HTML.span(class_='textField', c=[ HTML.input(value=value, name_=name, **kwargs), ])]), next, HTML.literal('<form:error name="%s" />' % name), expl])
def text(name, value=None, id=NotGiven, type="text", **attrs): """Create a standard text field. ``value`` is a string, the content of the text field. ``id`` is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through ``_make_safe_id_component()``. Pass None to suppress the ID attribute entirely. ``type`` is the input field type, normally "text". You can override it for HTML 5 input fields that don't have their own helper; e.g., "search", "email", "date". Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. The remaining keyword args will be standard HTML attributes for the tag. Example, a text input field:: >>> text("address") literal(%(u)s'<input id="address" name="address" type="text" />') HTML 5 example, a color picker: >>> text("color", type="color") literal(%(u)s'<input id="color" name="color" type="color" />') """ _set_input_attrs(attrs, type, name, value) _set_id_attr(attrs, id, name) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def checkbox(name, value="1", checked=False, label=None, id=None, **attrs): """Create a check box. Arguments: ``name`` -- the widget's name. ``value`` -- the value to return to the application if the box is checked. ``checked`` -- true if the box should be initially checked. ``label`` -- a text label to display to the right of the box. ``id`` is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through ``_make_safe_id_component()``. Pass the empty string ("") to suppress the ID attribute entirely. d The following HTML attributes may be set by keyword argument: * ``disabled`` - If true, checkbox will be grayed out. * ``readonly`` - If true, the user will not be able to modify the checkbox. To arrange multiple checkboxes in a group, see webhelpers.containers.distribute(). Example:: >>> checkbox("hi") literal(u'<input id="hi" name="hi" type="checkbox" value="1" />') """ _set_input_attrs(attrs, "checkbox", name, value) _set_id_attr(attrs, id, name) if checked: attrs["checked"] = "checked" convert_boolean_attrs(attrs, ["disabled", "readonly"]) widget = HTML.input(**attrs) if label: widget = HTML.label(widget, label) return widget
def text(name, value=None, id=NotGiven, type="text", **attrs): """Create a standard text field. ``value`` is a string, the content of the text field. ``id`` is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through ``_make_safe_id_component()``. Pass None to suppress the ID attribute entirely. ``type`` is the input field type, normally "text". You can override it for HTML 5 input fields that don't have their own helper; e.g., "search", "email", "date". Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. The remaining keyword args will be standard HTML attributes for the tag. Example, a text input field:: >>> text("address") literal(u'<input id="address" name="address" type="text" />') HTML 5 example, a color picker: >>> text("color", type="color") literal(u'<input id="color" name="color" type="color" />') """ _set_input_attrs(attrs, type, name, value) _set_id_attr(attrs, id, name) convert_boolean_attrs(attrs, ["disabled"]) return HTML.input(**attrs)
def checkbox(name, value="1", checked=False, label=None, id=None, **attrs): """Create a check box. Arguments: ``name`` -- the widget's name. ``value`` -- the value to return to the application if the box is checked. ``checked`` -- true if the box should be initially checked. ``label`` -- a text label to display to the right of the box. ``id`` is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through ``_make_safe_id_component()``. Pass the empty string ("") to suppress the ID attribute entirely. d The following HTML attributes may be set by keyword argument: * ``disabled`` - If true, checkbox will be grayed out. * ``readonly`` - If true, the user will not be able to modify the checkbox. To arrange multiple checkboxes in a group, see webhelpers.containers.distribute(). Example:: >>> checkbox("hi") literal(u'<input id="hi" name="hi" type="checkbox" value="1" />') """ _set_input_attrs(attrs, "checkbox", name, value) _set_id_attr(attrs, id, name) if checked: attrs["checked"] = "checked" convert_boolean_attrs(attrs, ["disabled", "readonly"]) widget = HTML.input(**attrs) if label: widget = HTML.label(widget, label) return widget
def form(url, method="post", multipart=False, **attrs): """An open tag for a form that will submit to ``url``. You must close the form yourself by calling ``end_form()`` or outputting </form>. Options: ``multipart`` If set to True, the enctype is set to "multipart/form-data". You must set it to true when uploading files, or the browser will submit the filename rather than the file. ``method`` The method to use when submitting the form, usually either "GET" or "POST". If "PUT", "DELETE", or another verb is used, a hidden input with name _method is added to simulate the verb over POST. Examples: >>> form("/submit") literal(u'<form action="/submit" method="post">') >>> form("/submit", method="get") literal(u'<form action="/submit" method="get">') >>> form("/submit", method="put") literal(u'<form action="/submit" method="post"><input name="_method" type="hidden" value="put" />') >>> form("/submit", "post", multipart=True) literal(u'<form action="/submit" enctype="multipart/form-data" method="post">') """ if multipart: attrs["enctype"] = "multipart/form-data" method_tag = literal("") if method.lower() in ['post', 'get']: attrs['method'] = method else: attrs['method'] = "post" method_tag = HTML.input(type="hidden", name="_method", value=method) attrs["action"] = url return HTML.form(method_tag, _closed=False, **attrs)
def form(url, method="post", multipart=False, **attrs): """An open tag for a form that will submit to ``url``. You must close the form yourself by calling ``end_form()`` or outputting </form>. Options: ``multipart`` If set to True, the enctype is set to "multipart/form-data". You must set it to true when uploading files, or the browser will submit the filename rather than the file. ``method`` The method to use when submitting the form, usually either "GET" or "POST". If "PUT", "DELETE", or another verb is used, a hidden input with name _method is added to simulate the verb over POST. Examples: >>> form("/submit") literal(u'<form action="/submit" method="post">') >>> form("/submit", method="get") literal(u'<form action="/submit" method="get">') >>> form("/submit", method="put") literal(u'<form action="/submit" method="post"><input name="_method" type="hidden" value="put" />') >>> form("/submit", "post", multipart=True) literal(u'<form action="/submit" enctype="multipart/form-data" method="post">') """ if multipart: attrs["enctype"] = "multipart/form-data" method_tag = literal("") if method.lower() in ['post', 'get']: attrs['method'] = method else: attrs['method'] = "post" method_tag = HTML.input(type="hidden", name="_method", value=method) attrs["action"] = url return HTML.form(method_tag, _closed=False, **attrs)
def radio_button(self, name, value, checked=False, show_errors=True, **options): """Creates a radio button. The id of the radio button will be set to the name + value with a _ in between to ensure its uniqueness. """ pretty_tag_value = re.sub(r'\s', "_", '%s' % value) pretty_tag_value = re.sub(r'(?!-)\W', "", pretty_tag_value).lower() html_options = {'type': 'radio', 'name_': name, 'value': value} html_options.update(options) if checked: html_options["checked"] = "checked" ret = HTML.input(**html_options) if show_errors: self.get_error(name) return ret
def check_box(self, name, value='1', checked=None, label='', show_errors=True, **options): """ Creates a check box. """ o = {'type': 'checkbox', 'name_': name, 'value': value} o.update(options) if checked == None and name in self.defaults: checked = self.defaults[name] if checked: o['checked'] = 'checked' ret = HTML.input(**o) if label: ret += ' ' + label if show_errors: ret += self.get_error(name) return ret
def text_field(self, name, value=None, show_errors=True, **options): """ Creates a standard text field. ``value`` is a string, the content of the text field Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. Remaining keyword options will be standard HTML options for the tag. """ o = {'type': 'text', 'name_': name, 'value': value} o.update(options) if o['value'] == None and name in self.defaults: o['value'] = self.defaults[name] ret = HTML.input(**o) if show_errors: ret += self.get_error(name) return ret
def text_field(self, name, value=None, show_errors=True, **options): """ Creates a standard text field. ``value`` is a string, the content of the text field Options: * ``disabled`` - If set to True, the user will not be able to use this input. * ``size`` - The number of visible characters that will fit in the input. * ``maxlength`` - The maximum number of characters that the browser will allow the user to enter. Remaining keyword options will be standard HTML options for the tag. """ o = {'type': 'text', 'name_': name, 'value': value} o.update(options) if o['value'] == None and name in self.defaults: o['value'] = self.defaults[name] ret = HTML.input(**o) if show_errors: ret += self.get_error(name) return ret
def submit(name, value, id=NotGiven, **attrs): """Create a submit button with the text ``value`` as the caption.""" _set_input_attrs(attrs, "submit", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)
def image_button(name, value, id=None, **attrs): return HTML.input(name=name, value=value, type='image', **attrs)
def submit(name, value, **attrs): """Create a submit button with the text ``value`` as the caption.""" set_input_attrs(attrs, "submit", name, value) return HTML.input(**attrs)
def hidden(name, value=None, **attrs): """Create a hidden field. """ _set_input_attrs(attrs, "hidden", name, value) return HTML.input(**attrs)
def hidden(name, value=None, id=NotGiven, **attrs): """Create a hidden field. """ _set_input_attrs(attrs, "hidden", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)
def secure_link(href, value='Submit', value_formatted=None, title=None, method='post', form_data=None, link_data=None, link_class='', parent_id=None, force_profile=False): #def secure_link(href, value='Submit', value_formatted=None, css_class='', title=None, rel=None, confirm_text=None, method='POST', json_form_complete_actions='', modal_params=None, data={}): """ Create two things: - A visible HTML form which POSTs some data along with an auth token - An invisible pretty-looking plain-text link which calls form.submit() Then use javascript to hide the form and show the pretty link @param href - can be supplied as a string or a tuple in the format (args, kwargs), this tuple will then be used to automatically create href_json @param href_json - an optional JSON url to post to can be provided, this will then activate an AJAX call, this is normally set automatically by providing a tuple for href (see above) @param javascript_json_complete_actions - a string of javascript that is activated on a successful AJAX call. Normally used to refresh parts of the page that have been updated from the successful AJAX call. """ if not value_formatted: value_formatted = value else: value_formatted = literal(value_formatted) if not form_data: form_data = {} if not link_data: link_data = {} # Setup Get string href ---- # the href could be passed a a tuple of (args,kwargs) for form() to create a JSON version to submit to # we need a text compatable href reguardless href_original = copy.deepcopy(href) if isinstance(href, tuple): args = href[0] kwargs = href[1] form_href = url(*args, **kwargs) kwargs['format'] = 'json' data_json = url(*args, **kwargs) #form_data = dict([(key.replace('_', '-' if '_' in key else key, form_data[key])) for key in form_data.keys()]) # GregM: Work out what to do is json_complete has not been defined manually, this could and will fail on odd cercumstances if not form_data.get('json_complete'): args = list(args) args[0] = action_single_map.get(args[0], args[0]) if kwargs.get('format'): del kwargs['format'] kwargs['action'] = 'show' action1 = ['remove'] if method == 'DELETE' or method == 'delete' else ['update'] action2 = ['update', [url(*args, **kwargs)], None, None] if parent_id: kwargs['id'] = parent_id action2[1].append(url(*args, **kwargs)) if args[0] == 'member' or force_profile: action2[1].append('/profile') form_data['json_complete'] = json.dumps([action1, action2]).replace('"',"'") # Do magic to convert all form & link _data to kwargs form_data = dict([ ('data-%s' % k.replace('_','-'), v if isinstance(v, basestring) else json.dumps(v)) for (k,v) in form_data.items() ]) link_data = dict([ ('data-%s' % k.replace('_','-'), v if isinstance(v, basestring) else json.dumps(v)) for (k,v) in link_data.items() ]) # Keep track of number of secure links created so they can all have unique hash's #hhash = hashlib.md5(uniqueish_id(href, value, vals)).hexdigest()[0:6] # GregM: Semi-unique ids required for selenium, these will be unique to every action (multiple of same action can exist) # hhash = re.sub(funky_chars, '_', re.sub(link_matcher, '', href)) + '_' + method # Create Form -------- #AllanC: without the name attribute here the AJAX/JSON does not function, WTF! took me ages to track down :( NOTE: if the name="submit" jQuery wont submit! a known problem!? hf = form(href_original, method=method, class_='hide_if_js', **form_data) + \ HTML.input(type="submit", value=value, name=value) + \ end_form() #, hl = HTML.a( value_formatted , href = '#', class_ = link_class + ' hide_if_nojs link_secure', # GregM: secure_show means js will show element and remove class (to stop dup processing of same element) title = title, **link_data ) return HTML.span(hf+hl, class_="secure_link") #+json_submit_script
def hidden(name, value=None, **attrs): """Create a hidden field. """ _set_input_attrs(attrs, "hidden", name, value) return HTML.input(**attrs)
def submit(name, value, id=None, **attrs): """Create a submit button with the text ``value`` as the caption.""" _set_input_attrs(attrs, "submit", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)
def input_hidden(name, value='', **kwargs): kwargs.setdefault('id', name) return HTML.div(class_='formField', id='%s-field' % kwargs['id'], c=[HTML.input(type='hidden', value=value, name_=name, **kwargs), HTML.literal('<form:error name="%s" />' % name)])
def button_to(name, url='', **html_attrs): """Generate a form containing a sole button that submits to ``url``. Use this method instead of ``link_to`` for actions that do not have the safe HTTP GET semantics implied by using a hypertext link. The parameters are the same as for ``link_to``. Any ``html_attrs`` that you pass will be applied to the inner ``input`` element. In particular, pass disabled = True/False as part of ``html_attrs`` to control whether the button is disabled. The generated form element is given the class 'button-to', to which you can attach CSS styles for display purposes. The submit button itself will be displayed as an image if you provide both ``type`` and ``src`` as followed: type='image', src='icon_delete.gif' The ``src`` path should be the exact URL desired. A previous version of this helper added magical prefixes but this is no longer the case. Example 1:: # inside of controller for "feeds" >> button_to("Edit", url(action='edit', id=3)) <form method="post" action="/feeds/edit/3" class="button-to"> <div><input value="Edit" type="submit" /></div> </form> Example 2:: >> button_to("Destroy", url(action='destroy', id=3), .. method='DELETE') <form method="POST" action="/feeds/destroy/3" class="button-to"> <div> <input type="hidden" name="_method" value="DELETE" /> <input value="Destroy" type="submit" /> </div> </form> Example 3:: # Button as an image. >> button_to("Edit", url(action='edit', id=3), type='image', .. src='icon_delete.gif') <form method="POST" action="/feeds/edit/3" class="button-to"> <div><input alt="Edit" src="/images/icon_delete.gif" type="image" value="Edit" /></div> </form> .. note:: This method generates HTML code that represents a form. Forms are "block" content, which means that you should not try to insert them into your HTML where only inline content is expected. For example, you can legally insert a form inside of a ``div`` or ``td`` element or in between ``p`` elements, but not in the middle of a run of text, nor can you place a form within another form. (Bottom line: Always validate your HTML before going public.) Changed in WebHelpers 1.2: Preserve case of "method" arg for XHTML compatibility. E.g., "POST" or "PUT" causes *method="POST"*; "post" or "put" causes *method="post"*. """ if html_attrs: tags.convert_boolean_attrs(html_attrs, ['disabled']) method_tag = '' method = html_attrs.pop('method', '') if method.upper() in ['PUT', 'DELETE']: method_tag = HTML.input( type='hidden', id='_method', name_='_method', value=method) if method.upper() in ('GET', 'POST'): form_method = method elif method in ('put', 'delete'): # preserve lowercasing of verb form_method = 'post' else: form_method = 'POST' url, name = url, name or url submit_type = html_attrs.get('type') img_source = html_attrs.get('src') if submit_type == 'image' and img_source: html_attrs["value"] = name html_attrs.setdefault("alt", name) else: html_attrs["type"] = "submit" html_attrs["value"] = name return HTML.form(method=form_method, action=url, class_="button-to", c=[HTML.div(method_tag, HTML.input(**html_attrs))])
def button_to(name, url='', **html_options): """Generate a form containing a sole button that submits to ``url``. Use this method instead of ``link_to`` for actions that do not have the safe HTTP GET semantics implied by using a hypertext link. The parameters are the same as for ``link_to``. Any ``html_options`` that you pass will be applied to the inner ``input`` element. In particular, pass disabled = True/False as part of ``html_options`` to control whether the button is disabled. The generated form element is given the class 'button-to', to which you can attach CSS styles for display purposes. The submit button itself will be displayed as an image if you provide both ``type`` and ``src`` as followed: type='image', src='icon_delete.gif' The ``src`` path should be the exact URL desired. A previous version of this helper added magical prefixes but this is no longer the case. Example 1:: # inside of controller for "feeds" >> button_to("Edit", url(action='edit', id=3)) <form method="POST" action="/feeds/edit/3" class="button-to"> <div><input value="Edit" type="submit" /></div> </form> Example 2:: >> button_to("Destroy", url(action='destroy', id=3), .. method='DELETE') <form method="POST" action="/feeds/destroy/3" class="button-to"> <div> <input type="hidden" name="_method" value="DELETE" /> <input value="Destroy" type="submit" /> </div> </form> Example 3:: # Button as an image. >> button_to("Edit", url(action='edit', id=3), type='image', .. src='icon_delete.gif') <form method="POST" action="/feeds/edit/3" class="button-to"> <div><input alt="Edit" src="/images/icon_delete.gif" type="image" value="Edit" /></div> </form> .. note:: This method generates HTML code that represents a form. Forms are "block" content, which means that you should not try to insert them into your HTML where only inline content is expected. For example, you can legally insert a form inside of a ``div`` or ``td`` element or in between ``p`` elements, but not in the middle of a run of text, nor can you place a form within another form. (Bottom line: Always validate your HTML before going public.) """ if html_options: convert_boolean_attrs(html_options, ['disabled']) method_tag = '' method = html_options.pop('method', '') if method.upper() in ['PUT', 'DELETE']: method_tag = HTML.input( type='hidden', id='_method', name_='_method', value=method) form_method = (method.upper() == 'GET' and method) or 'POST' url, name = url, name or url submit_type = html_options.get('type') img_source = html_options.get('src') if submit_type == 'image' and img_source: html_options["value"] = name html_options.setdefault("alt", name) else: html_options["type"] = "submit" html_options["value"] = name return HTML.form(method=form_method, action=url, class_="button-to", c=[HTML.div(method_tag, HTML.input(**html_options))])
def hidden(name, value=None, id=NotGiven, **attrs): """Create a hidden field. """ _set_input_attrs(attrs, "hidden", name, value) _set_id_attr(attrs, id, name) return HTML.input(**attrs)