docs: def _update_templatetype(templatetype, existing_tt=None):
      """
          Add or update a templatetype. If an existing template type is passed in,
          update that one. Otherwise search for an existing one. If not found, add.
      """
      if existing_tt is None:
          if "id" in templatetype and templatetype.id is not None:
              tmpltype_i = db.DBSession.query(TemplateType).filter(TemplateType.id == templatetype.id).one()
          else:
              tmpltype_i = TemplateType()
      else:
          tmpltype_i = existing_tt
  
      tmpltype_i.template_id = templatetype.template_id
      tmpltype_i.name        = templatetype.name
      tmpltype_i.description = templatetype.description
      tmpltype_i.alias       = templatetype.alias
  
      if templatetype.layout is not None:
          tmpltype_i.layout = get_layout_as_string(templatetype.layout)
  
      tmpltype_i.resource_type = templatetype.resource_type
  
      ta_dict = {}
      for t in tmpltype_i.typeattrs:
          ta_dict[t.attr_id] = t
  
      existing_attrs = []
  
      if templatetype.typeattrs is not None:
          for typeattr in templatetype.typeattrs:
              if typeattr.attr_id in ta_dict:
                  ta = _set_typeattr(typeattr, ta_dict[typeattr.attr_id])
                  existing_attrs.append(ta.attr_id)
              else:
                  ta = _set_typeattr(typeattr)
                  tmpltype_i.typeattrs.append(ta)
                  existing_attrs.append(ta.attr_id)
  
      log.debug("Deleting any type attrs not sent")
      for ta in ta_dict.values():
          if ta.attr_id not in existing_attrs:
              delete_typeattr(ta)
  
      if existing_tt is None:
          db.DBSession.add(tmpltype_i)
  
      return tmpltype_i