<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def update_template(template,**kwargs):
 """ Update template and a type and typeattrs. """

    tmpl = db.DBSession.query(Template).filter(Template.id==template.id).one()
    tmpl.name = template.name
    if template.description:
        tmpl.description = template.description

    #Lazy load the rest of the template
    for tt in tmpl.templatetypes:
        for ta in tt.typeattrs:
            ta.attr

    if template.layout:
        tmpl.layout = get_layout_as_string(template.layout)

    type_dict = dict([(t.id, t) for t in tmpl.templatetypes])
    existing_templatetypes = []

    if template.types is not None or template.templatetypes is not None:
        types = template.types if template.types is not None else template.templatetypes
        for templatetype in types:
            if templatetype.id is not None:
                type_i = type_dict[templatetype.id]
                _update_templatetype(templatetype, type_i)
                existing_templatetypes.append(type_i.id)
            else:
                #Give it a template ID if it doesn't have one
                templatetype.template_id = template.id
                new_templatetype_i = _update_templatetype(templatetype)
                existing_templatetypes.append(new_templatetype_i.id)

    for tt in tmpl.templatetypes:
        if tt.id not in existing_templatetypes:
            delete_templatetype(tt.id)

    db.DBSession.flush()

    return tmpl