Documentation ¶
Overview ¶
The View of MVC.
Index ¶
- Constants
- Variables
- func ClearAllCaches()
- func DecryptCookie(data []byte) (result []byte, err error)
- func EncryptCookie(data []byte) (result []byte, err error)
- func FindStaticFile(filename string) (filePath string, found bool, modifiedTime int64)
- func FindTemplateFile(filename string) (filePath string, found bool, modifiedTime int64)
- func GetFileUploadFormModel(form *Form, ctx *Context) (interface{}, error)
- func NewViewID(view View) (id string)
- func RenderChildViewsHTML(parent View, ctx *Context) (err error)
- func RenderTemplate(filename string, out io.Writer, context interface{}) (err error)
- func RenderTemplateString(tmplString string, name string, out io.Writer, context interface{}) (err error)
- func RunServer(paths *ViewPath)
- func RunServerAddr(addr string, paths *ViewPath)
- func TableHeaderRow(views ...View) func(ctx *Context) (Views, error)
- func TableHeaderRowEscape(s ...string) func(ctx *Context) (Views, error)
- type AllAuthenticators
- type AnyAuthenticator
- type Aside
- type Authenticator
- type BasicAuth
- type BoolAuth
- type Button
- type CSRFProtector
- type CachedView
- type Canvas
- type Checkbox
- type Comment
- type Configuration
- type ContactFormModel
- type Context
- type CookieSessionDataStore
- type CookieSessionTracker
- type Div
- type DummyImage
- type DynamicView
- type EscapeStringsListModel
- type EscapeStringsTableModel
- type FileInput
- type FileUploadFormModel
- type Forbidden
- type Form
- func (self *Form) AddMongoRefController(selector string, options model.Iterator)
- func (self *Form) DirectFieldLabel(metaData *model.MetaData) string
- func (self *Form) FieldInputClass(metaData *model.MetaData) string
- func (self *Form) FieldLabel(metaData *model.MetaData) string
- func (self *Form) GetCSRFProtector() CSRFProtector
- func (self *Form) GetErrorMessageClass() string
- func (self *Form) GetFieldControllers() FormFieldControllers
- func (self *Form) GetFieldDescription(metaData *model.MetaData) string
- func (self *Form) GetFieldDescriptionClass() string
- func (self *Form) GetInputSize(metaData *model.MetaData) int
- func (self *Form) GetLayout() FormLayout
- func (self *Form) GetRequiredMarker() View
- func (self *Form) GetSubmitButtonClass() string
- func (self *Form) GetSubmitButtonText() string
- func (self *Form) GetSuccessMessageClass() string
- func (self *Form) InputFieldPlaceholder(metaData *model.MetaData) string
- func (self *Form) IsFieldDisabled(field *model.MetaData) bool
- func (self *Form) IsFieldExcluded(field *model.MetaData, ctx *Context) bool
- func (self *Form) IsFieldHidden(field *model.MetaData) bool
- func (self *Form) IsFieldRequired(field *model.MetaData) bool
- func (self *Form) IsFieldVisible(field *model.MetaData, ctx *Context) bool
- func (self *Form) IsPost(request *Request) bool
- func (self *Form) Render(ctx *Context) (err error)
- type FormConfiguration
- type FormFieldController
- type FormFieldControllers
- func (self FormFieldControllers) Append(controllers ...FormFieldController) FormFieldControllers
- func (self FormFieldControllers) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)
- func (self FormFieldControllers) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error
- func (self FormFieldControllers) Supports(metaData *model.MetaData, form *Form) bool
- type FormLayout
- type Format
- type FrontController
- type GetFormModelFunc
- type GetModelIteratorFunc
- type GetModelIteratorViewFunc
- type GetTemplateContextFunc
- type HTML
- func BR() HTML
- func DivClearBoth() HTML
- func DummyText(length int) HTML
- func Escape(text string) HTML
- func GoogleAnalytics(trackingID string) HTML
- func GoogleMaps(apiKey string, sensor bool, callback string) HTML
- func HR() HTML
- func Printf(text string, args ...interface{}) HTML
- func PrintfEscape(text string, args ...interface{}) HTML
- func SCRIPT(script string) HTML
- func STYLE(css string) HTML
- func ScriptLink(url string) HTML
- func StylesheetLink(url string) HTML
- type HTMLStringsListModel
- type HTMLStringsTableModel
- type HiddenInput
- type If
- type Iframe
- type Image
- type IndexedStringsSelectModel
- func (self *IndexedStringsSelectModel) Disabled(index int) bool
- func (self *IndexedStringsSelectModel) IterateChildren(parent *Select, callback func(parent View, child View) (next bool))
- func (self *IndexedStringsSelectModel) NumOptions() int
- func (self *IndexedStringsSelectModel) RenderItem(index int, ctx *Context) (err error)
- func (self *IndexedStringsSelectModel) Selected(index int) bool
- func (self *IndexedStringsSelectModel) Value(index int) string
- type IterateChildrenCallback
- type JQueryDialog
- type Label
- type LabeledModelView
- type Link
- type LinkModel
- type List
- type ListModel
- type Menu
- type Middleware
- type ModalDialog
- type ModelBlobController
- func (self ModelBlobController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)
- func (self ModelBlobController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error
- func (self ModelBlobController) Supports(metaData *model.MetaData, form *Form) bool
- type ModelBoolController
- func (self ModelBoolController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)
- func (self ModelBoolController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error
- func (self ModelBoolController) Supports(metaData *model.MetaData, form *Form) bool
- type ModelChoiceController
- type ModelDateController
- type ModelDateTimeController
- type ModelDynamicChoiceController
- type ModelEmailController
- type ModelFileController
- func (self ModelFileController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)
- func (self ModelFileController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error
- func (self ModelFileController) Supports(metaData *model.MetaData, form *Form) bool
- type ModelFloatController
- type ModelIntController
- type ModelIteratorTableView
- type ModelIteratorView
- type ModelMultipleChoiceController
- func (self ModelMultipleChoiceController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)
- func (self ModelMultipleChoiceController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error
- func (self ModelMultipleChoiceController) Supports(metaData *model.MetaData, form *Form) bool
- type ModelPasswordController
- type ModelPhoneController
- type ModelStringController
- type ModelTextController
- type ModelUrlController
- type MongoRefController
- func (self *MongoRefController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)
- func (self *MongoRefController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error
- func (self *MongoRefController) Supports(metaData *model.MetaData, form *Form) bool
- type MultiViewsListModel
- type NotFound
- type NotFoundView
- type OnFormSubmitFunc
- type OnFormValidationErrorFunc
- type Page
- func (self *Page) Init(thisView View)
- func (self *Page) IterateChildren(callback IterateChildrenCallback)
- func (self *Page) LinkContent(ctx *Context) View
- func (self *Page) LinkRel(ctx *Context) string
- func (self *Page) LinkTitle(ctx *Context) string
- func (self *Page) Render(ctx *Context) (err error)
- func (self *Page) SetPath(path string)
- func (self *Page) URL(ctx *Context) string
- type PageConfiguration
- type PageLink
- type Paragraph
- type PermanentRedirect
- type Redirect
- type RedirectView
- type Render
- type RenderView
- type Renderer
- type Renderers
- type Request
- type Response
- func (self *Response) Abort(status int, body string)
- func (self *Response) AuthorizationRequired401()
- func (self *Response) Bytes() []byte
- func (self *Response) ContentDispositionAttachment(filename string)
- func (self *Response) Forbidden403(message string)
- func (self *Response) Header() http.Header
- func (self *Response) NotFound404(message string)
- func (self *Response) NotModified304()
- func (self *Response) PopBody() (bufferData []byte)
- func (self *Response) PopBodyString() (bufferData string)
- func (self *Response) Printf(format string, args ...interface{}) (n int, err error)
- func (self *Response) PushBody()
- func (self *Response) RedirectPermanently301(url string)
- func (self *Response) RedirectTemporary302(url string)
- func (self *Response) RequireHeadScript(script string, priority int)
- func (self *Response) RequireHeadScriptURL(url string, priority int)
- func (self *Response) RequireScript(script string, priority int)
- func (self *Response) RequireScriptURL(url string, priority int)
- func (self *Response) RequireStyle(css string, priority int)
- func (self *Response) RequireStyleURL(url string, priority int)
- func (self *Response) SetContentTypeByExt(ext string)
- func (self *Response) SetSecureCookie(name string, val string, age int64, path string)
- func (self *Response) String() string
- func (self *Response) Write(p []byte) (n int, err error)
- func (self *Response) WriteByte(c byte) error
- func (self *Response) WriteString(s string) (n int, err error)
- type Select
- type SelectModel
- type Session
- type SessionDataStore
- type SessionTracker
- type SetModelValueControllerBase
- type ShortTag
- type Span
- type StandardFormLayout
- func (self *StandardFormLayout) BeginFormContent(form *Form, ctx *Context, formContent *Views) error
- func (self *StandardFormLayout) BeginIndexedFields(indexedFields *model.MetaData, form *Form, ctx *Context, formContent *Views) error
- func (self *StandardFormLayout) BeginNamedFields(namedFields *model.MetaData, form *Form, ctx *Context, formContent *Views) error
- func (self *StandardFormLayout) EndFormContent(fieldValidationErrs, generalValidationErrs []error, form *Form, ctx *Context, ...) error
- func (self *StandardFormLayout) EndIndexedFields(indexedFields *model.MetaData, validationErr error, form *Form, ctx *Context, ...) error
- func (self *StandardFormLayout) EndNamedFields(namedFields *model.MetaData, validationErr error, form *Form, ctx *Context, ...) error
- func (self *StandardFormLayout) GetDefaultInputSize(metaData *model.MetaData) int
- func (self *StandardFormLayout) IndexedField(field *model.MetaData, validationErr error, form *Form, ctx *Context, ...) error
- func (self *StandardFormLayout) NamedField(field *model.MetaData, validationErr error, form *Form, ctx *Context, ...) error
- func (self *StandardFormLayout) NewAddButton(onclick string, form *Form) View
- func (self *StandardFormLayout) NewDownButton(disabled bool, onclick string, form *Form) View
- func (self *StandardFormLayout) NewFieldDescrtiption(description string, form *Form) View
- func (self *StandardFormLayout) NewFieldErrorMessage(message string, metaData *model.MetaData, form *Form) View
- func (self *StandardFormLayout) NewGeneralErrorMessage(message string, form *Form) View
- func (self *StandardFormLayout) NewHiddenInput(metaData *model.MetaData, form *Form) (View, error)
- func (self *StandardFormLayout) NewRemoveButton(onclick string, form *Form) View
- func (self *StandardFormLayout) NewSubmitButton(text, confirmationMessage string, form *Form) View
- func (self *StandardFormLayout) NewSuccessMessage(message string, form *Form) View
- func (self *StandardFormLayout) NewTableHeader(metaData *model.MetaData, form *Form) (View, error)
- func (self *StandardFormLayout) NewUpButton(disabled bool, onclick string, form *Form) View
- func (self *StandardFormLayout) SubmitError(message string, form *Form, ctx *Context, formContent *Views) error
- func (self *StandardFormLayout) SubmitSuccess(message string, form *Form, ctx *Context, formContent *Views) error
- type StaticFile
- type StringLink
- type StringURL
- type StringsSelectModel
- func (self *StringsSelectModel) Disabled(index int) bool
- func (self *StringsSelectModel) IterateChildren(parent *Select, callback func(parent View, child View) (next bool))
- func (self *StringsSelectModel) NumOptions() int
- func (self *StringsSelectModel) RenderItem(index int, ctx *Context) (err error)
- func (self *StringsSelectModel) Selected(index int) bool
- func (self *StringsSelectModel) Value(index int) string
- type SubmitButton
- type Table
- type TableModel
- type Tag
- type Template
- type TextArea
- type TextField
- type TextFieldType
- type TextPreview
- type URL
- type URLLink
- type URLWithArgs
- type Video
- type View
- func ABBR(longTitle, abbreviation string) View
- func B(content ...interface{}) View
- func CODE(content ...interface{}) View
- func DEL(content ...interface{}) View
- func DFN(content ...interface{}) View
- func EM(content ...interface{}) View
- func H1(content ...interface{}) View
- func H2(content ...interface{}) View
- func H3(content ...interface{}) View
- func H4(content ...interface{}) View
- func H5(content ...interface{}) View
- func H6(content ...interface{}) View
- func I(content ...interface{}) View
- func JQueryUIAutocomplete(domSelector string, options []string, minLength int) View
- func JQueryUIAutocompleteFromURL(domSelector string, dataURL URL, minLength int) View
- func NewView(content interface{}) View
- func NonProductionServerView(view View) View
- func P(content ...interface{}) View
- func PRE(content ...interface{}) View
- func ProductionServerView(view View) View
- func Q(content ...interface{}) View
- func RSSLink(title string, url URL) View
- func RequireHeadScript(script string, priority int) View
- func RequireHeadScriptURL(url string, priority int) View
- func RequireScript(script string, priority int) View
- func RequireScriptURL(url string, priority int) View
- func RequireStyle(css string, priority int) View
- func RequireStyleURL(url string, priority int) View
- func SECTION(class string, content ...interface{}) View
- func STRONG(content ...interface{}) View
- func UncacheView(cachedView *CachedView) View
- func WrapContents(contents ...interface{}) View
- type ViewBase
- type ViewBaseWithId
- type ViewPath
- type ViewURLWrapper
- func (self *ViewURLWrapper) ID() string
- func (self *ViewURLWrapper) Init(thisView View)
- func (self *ViewURLWrapper) IterateChildren(callback IterateChildrenCallback)
- func (self *ViewURLWrapper) Render(ctx *Context) (err error)
- func (self *ViewURLWrapper) SetPath(path string)
- func (self *ViewURLWrapper) URL(ctx *Context) string
- type ViewWithURL
- type Views
- type ViewsListModel
- type ViewsTableModel
Constants ¶
const ( TextAreaDefaultCols = 80 TextAreaDefaultRows = 3 )
const FormIDName = "gostart_form_id"
const LoremIpsum = "" /* 3101-byte string literal not displayed */
const ModalDialogCloseScript = "Avgrund.hide();"
const MultipartFormData = "multipart/form-data"
const PathFragmentPattern = "([a-zA-Z0-9_\\-\\.]+)"
Variables ¶
var Config = Configuration{ ListenAndServeAt: "0.0.0.0:80", TemplateSystem: &templatesystem.Mustache{}, Page: PageConfiguration{ Template: "html5boilerplate.html", DefaultCSS: "/style.css", DefaultMetaViewport: "width=device-width", }, Form: FormConfiguration{ DefaultLayout: &StandardFormLayout{ DefaultInputSize: 80, DefaultTableInputSize: 20, }, DefaultCSRFProtector: nil, DefaultSubmitButtonText: "Save", DefaultErrorMessageClass: "error", DefaultSuccessMessageClass: "success", DefaultFieldDescriptionClass: "description", DefaultRequiredMarker: HTML("<span class='required'>*</span>"), GeneralErrorMessageOnFieldError: "This form has errors", DefaultFieldControllers: FormFieldControllers{ ModelStringController{}, ModelTextController{}, ModelUrlController{}, ModelEmailController{}, ModelPasswordController{}, ModelIntController{}, ModelFloatController{}, ModelPhoneController{}, ModelBoolController{}, ModelChoiceController{}, ModelMultipleChoiceController{}, ModelDynamicChoiceController{}, ModelDateController{}, ModelDateTimeController{}, ModelFileController{}, ModelBlobController{}, }, }, LabeledModelViewLabelClass: "labeled-model-view-label", LabeledModelViewValueClass: "labeled-model-view-value", BaseDirs: []string{"."}, StaticDirs: []string{"static"}, TemplateDirs: []string{"templates"}, SessionTracker: &CookieSessionTracker{}, SessionDataStore: NewCookieSessionDataStore(), NamedAuthenticators: make(map[string]Authenticator), }
var PathFragmentRegexp = regexp.MustCompile(PathFragmentPattern)
var StructTagKey = "view"
Functions ¶
func ClearAllCaches ¶
func ClearAllCaches()
ClearAllCaches cals ClearCache() for all CachedView objects created with CacheView().
func DecryptCookie ¶
func EncryptCookie ¶
func FindStaticFile ¶
func FindTemplateFile ¶
func GetFileUploadFormModel ¶
GetFileUploadFormModel when set at Form.GetModel will create a file upload form. Form.Enctype will be set to "multipart/form-fata" *FileUploadFormModel will be passed as formModel at Form.OnSubmit
func RenderChildViewsHTML ¶
func RenderTemplate ¶
func RenderTemplateString ¶
func RunServer ¶
func RunServer(paths *ViewPath)
RunServer starts a webserver with the given paths. If paths is nil, only static files will be served.
func RunServerAddr ¶
RunServerAddr starts a webserver with the given paths and address. If paths is nil, only static files will be served.
Types ¶
type AllAuthenticators ¶
type AllAuthenticators []Authenticator
AllAuthenticators returns true if all of its authenticators return true.
func (AllAuthenticators) Authenticate ¶
func (self AllAuthenticators) Authenticate(ctx *Context) (ok bool, err error)
type AnyAuthenticator ¶
type AnyAuthenticator []Authenticator
AnyAuthenticator returns true if any of its authenticators returns true.
func (AnyAuthenticator) Authenticate ¶
func (self AnyAuthenticator) Authenticate(ctx *Context) (ok bool, err error)
type Aside ¶
type Aside struct { ViewBaseWithId Class string Style string Content View }
Aside represents a HTML aside element.
func (*Aside) IterateChildren ¶
func (self *Aside) IterateChildren(callback IterateChildrenCallback)
type Authenticator ¶
type Authenticator interface { // Authenticate returns the auth result in ok, // err is used for real errors not negative authentication Authenticate(ctx *Context) (ok bool, err error) }
Authenticator authenticates the user of a request context.
func NamedAuthenticator ¶
func NamedAuthenticator(name string) (auth Authenticator, ok bool)
type BasicAuth ¶
BasicAuth implements HTTP basic auth as Authenticator.
func NewBasicAuth ¶
NewBasicAuth creates a BasicAuth instance with a single username and password.
type BoolAuth ¶
type BoolAuth bool
BoolAuth always returns its value at Authenticate(). Can be used for debugging.
type Button ¶
type Button struct { ViewBaseWithId Name string Class string Disabled bool TabIndex int OnClick string OnClickConfirm string // Will add a confirmation dialog for onclick Content View // Only used when Submit is false }
func ModalDialogCloseButton ¶
func (*Button) IterateChildren ¶
func (self *Button) IterateChildren(callback IterateChildrenCallback)
type CSRFProtector ¶
type CachedView ¶
type CachedView struct { ViewBaseWithId Content View Duration time.Duration // contains filtered or unexported fields }
CachedView implements ViewWithURL. If Content implements ViewWithURL too, the ViewWithURL methods will be forwarded to Content. Else CachedView provides its own implementation of ViewWithURL. Caching will be disabled, when the request is not a GET or has url parameters.
func CacheView ¶
func CacheView(duration time.Duration, view View) *CachedView
CacheView caches view for duration by wrapping it with a CachedView object. The CachedView is added to an internal list so that ClearAllCaches() can call ClearCache() on every CachedView. UncacheView() removes the CachedView from the internal list.
func (*CachedView) ClearCache ¶
func (self *CachedView) ClearCache()
func (*CachedView) IterateChildren ¶
func (self *CachedView) IterateChildren(callback IterateChildrenCallback)
func (*CachedView) Render ¶
func (self *CachedView) Render(ctx *Context) (err error)
func (*CachedView) SetPath ¶
func (self *CachedView) SetPath(path string)
func (*CachedView) URL ¶
func (self *CachedView) URL(ctx *Context) string
type Checkbox ¶
type Checkbox struct { ViewBaseWithId Name string Label string Checked bool Disabled bool Class string }
Checkbox represents a HTML input element of type checkbox.
type Comment ¶
type Comment string
func (Comment) IterateChildren ¶
func (self Comment) IterateChildren(callback IterateChildrenCallback)
type Configuration ¶
type Configuration struct { ListenAndServeAt string IsProductionServer bool // IsProductionServer will be set to true if localhost resolves to one of ProductionServerIPs ProductionServerIPs []string TemplateSystem templatesystem.Implementation Page PageConfiguration Form FormConfiguration LabeledModelViewLabelClass string LabeledModelViewValueClass string DisableCachedViews bool BaseDirs []string StaticDirs []string TemplateDirs []string RedirectSubdomains []string // Exapmle: "www" SiteName string CookieSecret string SessionTracker SessionTracker SessionDataStore SessionDataStore OnPreAuth func(ctx *Context) error GlobalAuth Authenticator // Will allways be used before all other authenticators FallbackAuth Authenticator // Will be used when no other authenticator is defined for the view NamedAuthenticators map[string]Authenticator LoginSignupPage **Page // Middlewares []Middleware Debug struct { ListenAndServeAt string Mode bool // Will be set to true if IsProductionServer is false LogPaths bool LogRedirects bool } // contains filtered or unexported fields }
func (*Configuration) Close ¶
func (self *Configuration) Close() error
func (*Configuration) Init ¶
func (self *Configuration) Init() error
func (*Configuration) Name ¶
func (self *Configuration) Name() string
type ContactFormModel ¶
type ContactFormModel struct { Name model.String `view:"label=Your name" model:"maxlen=40"` Email model.Email `view:"label=Your email address" model:"required|maxlen=40"` Subject model.String `view:"label=Subject" model:"maxlen=40"` Message model.Text `view:"label=Your message|cols=40|rows=10" model:"required"` }
ContactFormModel is a default form model for contact forms.
type Context ¶
type Context struct { Request *Request Response *Response Session *Session // View that responds to the HTTP request RespondingView View // Arguments parsed from the URL path URLArgs []string // Custom response wide data that can be set by the application Data interface{} DebugData interface{} }
func (*Context) ForURLArgs ¶
ForURLArgs returns an altered Context copy where Context.URLArgs is set to urlArgs. Can be used for calling the the URL() method of a URL interface to get the URL of another view, defined by urlArgs.
The following example gets the URL of MyPage with the first URL argument is that of the current page and the second URL argument is "second-arg":
MyPage.URL(ctx.ForURLArgs(ctx.URLArgs[0], "second-arg"))
func (*Context) ForURLArgsConvert ¶
type CookieSessionDataStore ¶
type CookieSessionDataStore struct {
// contains filtered or unexported fields
}
func (*CookieSessionDataStore) Delete ¶
func (self *CookieSessionDataStore) Delete(ctx *Context) (err error)
func (*CookieSessionDataStore) Get ¶
func (self *CookieSessionDataStore) Get(ctx *Context, data interface{}) (ok bool, err error)
func (*CookieSessionDataStore) Set ¶
func (self *CookieSessionDataStore) Set(ctx *Context, data interface{}) (err error)
type CookieSessionTracker ¶
type CookieSessionTracker struct { }
http://en.wikipedia.org/wiki/HTTP_cookie
func (*CookieSessionTracker) DeleteID ¶
func (self *CookieSessionTracker) DeleteID(ctx *Context)
func (*CookieSessionTracker) ID ¶
func (self *CookieSessionTracker) ID(ctx *Context) (id string, ok bool)
func (*CookieSessionTracker) SetID ¶
func (self *CookieSessionTracker) SetID(ctx *Context, id string)
type Div ¶
type Div struct { ViewBaseWithId Class string Style string Content View OnClick string }
Div represents a HTML div element.
func (*Div) IterateChildren ¶
func (self *Div) IterateChildren(callback IterateChildrenCallback)
type DummyImage ¶
type DummyImage struct { ViewBaseWithId Class string Width int Height int BackgroundColor string ForegroundColor string Text string }
DummyImage represents a HTML img element with src utilizing http://dummyimage.com.
func NewDummyImage ¶
func NewDummyImage(width, height int) *DummyImage
func (*DummyImage) Render ¶
func (self *DummyImage) Render(ctx *Context) (err error)
type DynamicView ¶
DynamicView implements View for a function that creates and renders a dynamic child-view in the Render method.
Example:
dynamicView := DynamicView( func(ctx *Context) (view View, err error) { return HTML("return dynamic created views here"), nil }, )
func DynamicViewBindURLArgs ¶
func DynamicViewBindURLArgs(getViewFunc interface{}) DynamicView
DynamicViewBindURLArgs creates a View where getViewFunc is called from View.Render with Context.URLArgs converted to function arguments. The first getViewFunc argument can be of type *Context, but this is optional. All further arguments will be converted from the corresponding Context.URLArgs string to their actual type. Conversion to integer, float, string and bool arguments are supported. If there are more URLArgs than function args, then supernumerous URLArgs will be ignored. If there are less URLArgs than function args, then the function args will receive their types zero value. The first result value of getViewFunc has to be of type View, the second result is optional and of type error.
Example:
view.DynamicViewBindURLArgs(func(i int, b bool) view.View { return view.Printf("ctx.URLArgs[0]: %d, ctx.URLArgs[1]: %b", i, b) })
func ViewOrError ¶
func ViewOrError(view View, err error) DynamicView
ViewOrError returns a DynamicView that renders view if err is nil or else renders the error.
func (DynamicView) ID ¶
func (self DynamicView) ID() string
func (DynamicView) Init ¶
func (self DynamicView) Init(thisView View)
func (DynamicView) IterateChildren ¶
func (self DynamicView) IterateChildren(callback IterateChildrenCallback)
func (DynamicView) Render ¶
func (self DynamicView) Render(ctx *Context) error
type EscapeStringsListModel ¶
type EscapeStringsListModel []string
func (EscapeStringsListModel) ItemView ¶
func (self EscapeStringsListModel) ItemView(index int, ctx *Context) (view View, err error)
func (EscapeStringsListModel) NumItems ¶
func (self EscapeStringsListModel) NumItems() int
type EscapeStringsTableModel ¶
type EscapeStringsTableModel [][]string
func (EscapeStringsTableModel) Columns ¶
func (self EscapeStringsTableModel) Columns() int
func (EscapeStringsTableModel) Rows ¶
func (self EscapeStringsTableModel) Rows() int
type FileUploadFormModel ¶
type Form ¶
type Form struct { ViewBaseWithId Class string Style string Action string // Default is "." plus any URL params Method string // Default is POST // If there are multiple forms on one page, then every form // needs a unique FormID, because the POST request with the form // data is made to the same URL or the page. // FormID can be empty if there is only one form on a page, // but it's good practice to always assign a FormID, because then // forms later added to the page won't lead to conflicts. FormID string CSRFProtector CSRFProtector Layout FormLayout // Config.Form.DefaultLayout will be used if nil FieldControllers FormFieldControllers // Config.Form.DefaultFieldControllers will be used in nil // GetModel returns the data-model used to create the form fields // and will receive changes from a form submit. // Thus, the model must be setable by reflection. // Be careful to not return the same model object at every call, // because the changed model from a submit will then be re-used // at a later form display which is usually not wanted. // Use the wrapper function FormModel() only when the form is // embedded in a DynamicView and the model argument is dynamically // created per View render. GetModel GetFormModelFunc // ModelFieldAuth maps a field selector to an Authenticator. // Fields that match the selector will only be displayed if the // Authenticator returns true. ModelFieldAuth map[string]Authenticator /* OnSubmit is called after the form was submitted by the user and did not contain any validation errors. If the OnSubmit result err is nil and the redirect result or Form.Redirect is not nil, then a HTTP redirect will be issued. Else if the OnSubmit result message is not empty, it will be displayed in the form regardless of the result err. If the results message and err are nil, then Form.SuccessMessage will be displayed in the form. If the result err is not nil and message is empty, then err will be displayed in the form. Else message will be displayed. This can be used to return a readable error message for the user via message and an internal error for logging via err. */ OnSubmit OnFormSubmitFunc // OnValidationError is called when the form model failed to validate. OnValidationError OnFormValidationErrorFunc // NewFieldInput is a hook that will be called instead of FieldFactory.NewInput // if not nil. Can be used for form specific alterations to the form layout. NewFieldInput func(withLabel bool, metaData *model.MetaData, form *Form) (View, error) ModelMaxDepth int // if zero, no depth limit ExcludedFields []string // Use point notation for nested fields. In case of arrays/slices use wildcards HiddenFields []string // Use point notation for nested fields. In case of arrays/slices use wildcards DisabledFields []string // Use point notation for nested fields RequiredFields []string // Also available as static struct field tag. Use point notation for nested fields Labels map[string]string FieldDescriptions map[string]string InputSizes map[string]int ErrorMessageClass string // If empty, Config.Form.DefaultErrorMessageClass will be used SuccessMessageClass string // If empty, Config.Form.DefaultSuccessMessageClass will be used FieldDescriptionClass string GeneralErrorOnFieldError bool RequiredMarker View // If nil, Config.Form.DefaultRequiredMarker will be used SuccessMessage string SubmitButtonText string SubmitButtonClass string SubmitButtonConfirm string // Will add a confirmation dialog for onclick Redirect URL // 302 redirect after successful OnSubmit() ShowRefIDs bool Enctype string }
Form creates an input form for a data model.
Gists:
https://gist.github.com/3748164
Note:
CSRF protection is not implemented yet
The data model:
The default behavior of Form is to send a POST request with the form data to the same URL of the page it is located in. Form then takes the values from the POST request and sets them at the data model and then validates the model.
If there are multiple forms on one page, then every form needs a unique FormID, because the POST request with the form data is made to the same URL or the page. FormID can be empty if there is only one form on a page, but it's good practice to always assign a FormID, because then forms later added to the page won't lead to conflicts.
The model for the form is provided the GetModel function. It can be a struct of model.Value implementations like model.String or model.Bool or a slice of model.DynamicValue (which is available as type model.DynamicValues with additional methods). If the model was declared as variable before the form, then the helper function FormModel() can be used for GetModel. Note that model structs are always passed on as pointers.
Example:
var structModel struct { A, B model.Bool } &Form{ GetModel: FormModel(&structModel), } &Form{ GetModel: func(form *Form, ctx *Context) (interface{}, error) { dynamicModel := model.DynamicValues{ {Name: "A": Value: model.NewBool(true)}, {Name: "B": Value: model.NewString("go-start is awesome")}, {Name: "C": Value: model.NewString("Required")}, } dynamicModel[2].SetAttrib("model", "required", "true") return dynamicModel, nil } }
The names of the exported struct fields or model.DynamicValue.Name is used as label for the generated form fields. The labels of struct fields can be overridden by adding a view tag like `view:"label=Hello World!".
Example:
type MyModel struct { AnInt model.Int // Label will be "AnInt" Overr model.String `view:"label=A String" // Label will be "A String" }
Labels can also be overridden on a per form basis by setting Form.Labels which is a map[string]string. The "selector" of a field is used as key and the label as value in the map.
Form field selectors:
A selector is the path of struct field names or model.DynamicValue.Name from the root of the model to the described concatenated by ".". In case of slice or array fields, the index is used as field name. The wildcard character $ can be used to select all fields of a slice or array.
Example:
type MyModel struct { A model.String B struct { X model.Int } C [2]struct{ Y model.Int } } "A" selects MyModel.A "B.X" selects MyModel.B.X "C.1.Y" selects MyModel.C[1].Y "C.$.Y" selects MyModel.C[0].Y and MyModel.C[1].Y
Selectors can also be used to mark data model fields as required, excluded, hidden, disabled by setting them at Form.RequiredFields, Form.ExcludedFields, Form.HiddenFields and Form.DisabledFields. Required fields must not be empty to validate. Hidden fields generate hidden HTML form input elements, whereas excluded fields are completely ignored.
required can also be set as model tag, hidden and disabled as view tags at struct fields of the data model.
Example:
var myModel struct { Required1 model.String `model:"required"` Required2 model.Int Hidden1 model.Float `view:"hidden"` Hidden2 model.Url Disabled1 model.Bool `view:"disabled"` Disabled2 model.Email Excluded model.String } &Form{ RequiredFields: []string{"Required2"}, HiddenFields: []string{"Hidden2"}, DisabledFields: []string{"Disabled2"}, ExcludedFields: []string{"Excluded"}, GetModel: FormModel(&myModel), }
Data validation:
All model.Value implementations also implement model.Validator. Custom model wide validation can be achieved by implementing model.Validator for the whole model or parts of it.
Example from user/formmodels.go:
type PasswordFormModel struct { Password1 model.Password `model:"minlen=6" view:"label=Password|size=20"` Password2 model.Password `view:"label=Repeat password|size=20"` } func (self *PasswordFormModel) Validate(metaData *model.MetaData) error { if self.Password1 != self.Password2 { return errors.New("Passwords don't match") } return nil }
If there were any validations errors Form.OnValidationError will be called if not nil, or else Form.OnSubmit.
Processing the submitted data:
Form.OnSubmit returns three values: (message string, redirect URL, err error) If error is nil and redirect is not nil, then a redirect response will be sent. Without redirect message will be displayed if not empty. The message will be styled as success message if err is nil, else as error message. If message is empty and err is not nil, then err will be displayed as error message. Keep in mind, that users of a website are not interested in technical details of internal errors, they can even be used to hack the website. So use message to return a sanitized message for the user and error for internal logging.
Form layout:
todo
Slices and arrays in the data model will be displayed as table by StandardFormLayout ¶
Styling:
todo
func NewContactForm ¶
NewContactForm creates a new contact form that sends submitted data to recipientEmail.
func (*Form) AddMongoRefController ¶
func (*Form) DirectFieldLabel ¶
DirectFieldLabel returns a label for a form field generated from metaData. It creates the label only from the name or label tag of metaData, not including its parents.
func (*Form) FieldLabel ¶
FieldLabel returns a label for a form field generated from metaData. It creates the label from the names or label tags of metaData and all its parents, starting with the root parent, concanated with a space character.
func (*Form) GetCSRFProtector ¶
func (self *Form) GetCSRFProtector() CSRFProtector
GetCSRFProtector returns self.CSRFProtector if not nil, else Config.Form.DefaultCSRFProtector will be returned.
func (*Form) GetErrorMessageClass ¶
func (*Form) GetFieldControllers ¶
func (self *Form) GetFieldControllers() FormFieldControllers
GetFieldControllers returns self.FieldControllers if not nil, else Config.Form.DefaultFieldControllers will be returned.
func (*Form) GetFieldDescription ¶
func (*Form) GetFieldDescriptionClass ¶
func (*Form) GetLayout ¶
func (self *Form) GetLayout() FormLayout
GetLayout returns self.Layout if not nil, else Config.Form.DefaultLayout will be returned.
func (*Form) GetRequiredMarker ¶
func (*Form) GetSubmitButtonClass ¶
func (*Form) GetSubmitButtonText ¶
Returns self.SubmitButtonText if not empty, else Config.Form.DefaultSubmitButtonText
func (*Form) GetSuccessMessageClass ¶
func (*Form) InputFieldPlaceholder ¶
func (*Form) IsFieldExcluded ¶
IsFieldExcluded returns weather a field will be excluded from the form. Fields will be excluded, if their selector matches one in Form.ExcludedFields or if a matching Authenticator from Form.ModelFieldAuth returns false. A field is also excluded when its parent field is excluded. This function is not restricted to model.Value, it works with all struct fields. This way a whole sub struct an be excluded by adding its selector to Form.ExcludedFields.
func (*Form) IsFieldHidden ¶
IsFieldHidden returns if a hidden input element will be created for a form field. Hidden fields are not validated.
func (*Form) IsFieldVisible ¶
IsFieldVisible returns if the FormFieldFactory can create an input widget for the field, and if the field neither hidden or excluded. Only visible fields are validated. IsFieldExcluded and IsFieldHidden have different semantics.
type FormConfiguration ¶
type FormConfiguration struct { DefaultLayout FormLayout DefaultCSRFProtector CSRFProtector DefaultErrorMessageClass string DefaultSuccessMessageClass string DefaultSubmitButtonClass string DefaultFieldDescriptionClass string StandardFormLayoutDivClass string DefaultSubmitButtonText string GeneralErrorMessageOnFieldError string DefaultRequiredMarker View DefaultFieldControllers FormFieldControllers }
type FormFieldController ¶
type FormFieldController interface { // Supports returns if this controller supports a model with the given metaData. Supports(metaData *model.MetaData, form *Form) bool // NewInput creates a new form field input view for the model metaData. NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error) // SetValue sets the value of the model from HTTP POST form data. SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error }
FormFieldController is a MVC controller for form fields.
type FormFieldControllers ¶
type FormFieldControllers []FormFieldController
func (FormFieldControllers) Append ¶
func (self FormFieldControllers) Append(controllers ...FormFieldController) FormFieldControllers
type FormLayout ¶
type FormLayout interface { GetDefaultInputSize(metaData *model.MetaData) int BeginFormContent(form *Form, ctx *Context, formContent *Views) error // SubmitSuccess will be called before EndFormContent if there were no // validation errors of the posted form data and Form.OnSubmit has // not returned an error. SubmitSuccess(message string, form *Form, ctx *Context, formContent *Views) error // SubmitError will be called before EndFormContent if there were no // validation errors of the posted form data and Form.OnSubmit has // returned an error. SubmitError(message string, form *Form, ctx *Context, formContent *Views) error EndFormContent(fieldValidationErrs, generalValidationErrs []error, form *Form, ctx *Context, formContent *Views) error BeginNamedFields(namedFields *model.MetaData, form *Form, ctx *Context, formContent *Views) error NamedField(field *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error EndNamedFields(namedFields *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error BeginIndexedFields(indexedFields *model.MetaData, form *Form, ctx *Context, formContent *Views) error IndexedField(field *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error EndIndexedFields(indexedFields *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error NewHiddenInput(metaData *model.MetaData, form *Form) (View, error) NewTableHeader(metaData *model.MetaData, form *Form) (View, error) NewFieldDescrtiption(description string, form *Form) View NewFieldErrorMessage(message string, metaData *model.MetaData, form *Form) View NewGeneralErrorMessage(message string, form *Form) View NewSuccessMessage(message string, form *Form) View NewSubmitButton(text, confirmationMessage string, form *Form) View NewAddButton(onclick string, form *Form) View NewRemoveButton(onclick string, form *Form) View NewUpButton(disabled bool, onclick string, form *Form) View NewDownButton(disabled bool, onclick string, form *Form) View }
FormLayout is responsible for creating and structuring all dynamic content of the form including the submit button. It uses Form.GetFieldFactory() to create the field views.
type FrontController ¶
type FrontController func(content View) ViewWithURL
func (FrontController) ContentFunc ¶
func (self FrontController) ContentFunc(contentFunc interface{}) ViewWithURL
type GetFormModelFunc ¶
func FormModel ¶
func FormModel(model interface{}) GetFormModelFunc
type GetModelIteratorFunc ¶
func ModelIterator ¶
func ModelIterator(iter model.Iterator) GetModelIteratorFunc
type GetTemplateContextFunc ¶
func TemplateContext ¶
func TemplateContext(context interface{}) GetTemplateContextFunc
type HTML ¶
type HTML string
func DivClearBoth ¶
func DivClearBoth() HTML
func GoogleAnalytics ¶
func GoogleMaps ¶
todo: replace http with https if necessary
func PrintfEscape ¶
PrintfEscape creates an escaped HTML string.
func ScriptLink ¶
func StylesheetLink ¶
func (HTML) IterateChildren ¶
func (self HTML) IterateChildren(callback IterateChildrenCallback)
type HTMLStringsListModel ¶
type HTMLStringsListModel []string
func (HTMLStringsListModel) ItemView ¶
func (self HTMLStringsListModel) ItemView(index int, ctx *Context) (view View, err error)
func (HTMLStringsListModel) NumItems ¶
func (self HTMLStringsListModel) NumItems() int
type HTMLStringsTableModel ¶
type HTMLStringsTableModel [][]string
func (HTMLStringsTableModel) Columns ¶
func (self HTMLStringsTableModel) Columns() int
func (HTMLStringsTableModel) Rows ¶
func (self HTMLStringsTableModel) Rows() int
type HiddenInput ¶
type HiddenInput struct { ViewBaseWithId Name string Value string }
func (*HiddenInput) Render ¶
func (self *HiddenInput) Render(ctx *Context) (err error)
type If ¶
type If struct { ViewBaseWithId Condition bool Content View ElseContent View }
func (*If) IterateChildren ¶
func (self *If) IterateChildren(callback IterateChildrenCallback)
type Iframe ¶
type Iframe struct { ViewBaseWithId Class string Width int Height int Border int Scrolling bool MarginWidth int MarginHeight int Seamless bool URL string }
func GoogleMapsIframe ¶
type Image ¶
type Image struct { ViewBaseWithId Class string URL URL // If URL is set, then Src will be ignored Src string // String URL of the image, used when URL is nil Width int Height int Title string }
type IndexedStringsSelectModel ¶
func (*IndexedStringsSelectModel) Disabled ¶
func (self *IndexedStringsSelectModel) Disabled(index int) bool
func (*IndexedStringsSelectModel) IterateChildren ¶
func (self *IndexedStringsSelectModel) IterateChildren(parent *Select, callback func(parent View, child View) (next bool))
func (*IndexedStringsSelectModel) NumOptions ¶
func (self *IndexedStringsSelectModel) NumOptions() int
func (*IndexedStringsSelectModel) RenderItem ¶
func (self *IndexedStringsSelectModel) RenderItem(index int, ctx *Context) (err error)
func (*IndexedStringsSelectModel) Selected ¶
func (self *IndexedStringsSelectModel) Selected(index int) bool
func (*IndexedStringsSelectModel) Value ¶
func (self *IndexedStringsSelectModel) Value(index int) string
type IterateChildrenCallback ¶
type JQueryDialog ¶
Dependencies of jQuery UI Dialog are not included.
func (*JQueryDialog) CloseScript ¶
func (self *JQueryDialog) CloseScript() string
func (*JQueryDialog) OpenScript ¶
func (self *JQueryDialog) OpenScript() string
func (*JQueryDialog) Render ¶
func (self *JQueryDialog) Render(ctx *Context) (err error)
type LabeledModelView ¶
type LabeledModelView struct { ViewBase Model interface{} Labels map[string]string ExcludedFields []string HideEmpty bool }
LabeledModelView displays a Model similar to Form, but with immutable strings instead of input fields.
func NewLabeledModelView ¶
func NewLabeledModelView(model interface{}) *LabeledModelView
func (*LabeledModelView) DirectFieldLabel ¶
func (self *LabeledModelView) DirectFieldLabel(metaData *model.MetaData) string
DirectFieldLabel returns a label for a model field generated from metaData. It creates the label only from the name or label tag of metaData, not including its parents.
func (*LabeledModelView) FieldLabel ¶
func (self *LabeledModelView) FieldLabel(metaData *model.MetaData) string
FieldLabel returns a label for a model field generated from metaData. It creates the label from the names or label tags of metaData and all its parents, starting with the root parent, concanated with a space character.
func (*LabeledModelView) IsFieldExcluded ¶
func (self *LabeledModelView) IsFieldExcluded(field *model.MetaData) bool
IsFieldExcluded returns weather a field will be excluded. Fields will be excluded, if their selector matches one in LabeledModelView.ExcludedFields. A field is also excluded when its parent field is excluded. This function is not restricted to model.Value, it works with all struct fields. This way a whole sub struct an be excluded by adding its selector to LabeledModelView.ExcludedFields.
func (*LabeledModelView) Render ¶
func (self *LabeledModelView) Render(ctx *Context) (err error)
type Link ¶
type Link struct { ViewBaseWithId Class string Model LinkModel NewWindow bool }
func A_blank ¶
func A_blank(url interface{}, content ...interface{}) *Link
A_blank creates a HTML link with target="_blank"
func A_blank_nofollow ¶
func A_blank_nofollow(url interface{}, content ...interface{}) *Link
A_blank creates a HTML link with target="_blank" and rel="nofollow"
func A_nofollow ¶
func A_nofollow(url interface{}, content ...interface{}) *Link
A creates a HTML link.
type LinkModel ¶
type LinkModel interface { URL LinkContent(ctx *Context) View LinkTitle(ctx *Context) string LinkRel(ctx *Context) string }
func NewLinkModel ¶
func NewLinkModel(url interface{}, content ...interface{}) LinkModel
func NewLinkModelRel ¶
type List ¶
type List struct { ViewBaseWithId Model ListModel Ordered bool OrderOffset uint Class string }
TODO definition list
func OL ¶
func OL(items ...interface{}) *List
Ul is a shortcut to create an ordered list by wrapping items as HTML views. NewView will be called for every passed item.
type Menu ¶
type Middleware ¶
type ModalDialog ¶
type ModalDialog struct { ViewBaseWithId Class string Style string Content View }
func (*ModalDialog) IterateChildren ¶
func (self *ModalDialog) IterateChildren(callback IterateChildrenCallback)
func (*ModalDialog) OpenButton ¶
func (self *ModalDialog) OpenButton(text string) *Button
func (*ModalDialog) OpenScript ¶
func (self *ModalDialog) OpenScript() string
func (*ModalDialog) Render ¶
func (self *ModalDialog) Render(ctx *Context) (err error)
type ModelBlobController ¶
type ModelBlobController struct{}
type ModelBoolController ¶
type ModelBoolController struct{}
type ModelChoiceController ¶
type ModelChoiceController struct {
SetModelValueControllerBase
}
type ModelDateController ¶
type ModelDateController struct {
SetModelValueControllerBase
}
type ModelDateTimeController ¶
type ModelDateTimeController struct {
SetModelValueControllerBase
}
type ModelDynamicChoiceController ¶
type ModelDynamicChoiceController struct {
SetModelValueControllerBase
}
type ModelEmailController ¶
type ModelEmailController struct {
SetModelValueControllerBase
}
type ModelFileController ¶
type ModelFileController struct{}
type ModelFloatController ¶
type ModelFloatController struct {
SetModelValueControllerBase
}
type ModelIntController ¶
type ModelIntController struct {
SetModelValueControllerBase
}
type ModelIteratorTableView ¶
type ModelIteratorTableView struct { ViewBase Class string Caption string GetModelIterator GetModelIteratorFunc GetHeaderRowViews func(ctx *Context) (views Views, err error) GetRowViews func(row int, rowModel interface{}, ctx *Context) (views Views, err error) // contains filtered or unexported fields }
func (*ModelIteratorTableView) IterateChildren ¶
func (self *ModelIteratorTableView) IterateChildren(callback IterateChildrenCallback)
func (*ModelIteratorTableView) Render ¶
func (self *ModelIteratorTableView) Render(ctx *Context) (err error)
type ModelIteratorView ¶
type ModelIteratorView struct { ViewBase GetModelIterator GetModelIteratorFunc GetModelIteratorView GetModelIteratorViewFunc // nil Views will be ignored }
func (*ModelIteratorView) Render ¶
func (self *ModelIteratorView) Render(ctx *Context) (err error)
type ModelMultipleChoiceController ¶
type ModelMultipleChoiceController struct{}
type ModelPasswordController ¶
type ModelPasswordController struct {
SetModelValueControllerBase
}
type ModelPhoneController ¶
type ModelPhoneController struct {
SetModelValueControllerBase
}
type ModelStringController ¶
type ModelStringController struct {
SetModelValueControllerBase
}
type ModelTextController ¶
type ModelTextController struct {
SetModelValueControllerBase
}
type ModelUrlController ¶
type ModelUrlController struct {
SetModelValueControllerBase
}
type MongoRefController ¶
type MongoRefController struct { Selector string // Empty string matches all selectors OptionsIterator model.Iterator // GetLabel returns the label of a referenced document. // If GetLabel is nil, then the String() method of // the doc will be used. GetLabel func(doc interface{}) string }
func NewMongoRefController ¶
func NewMongoRefController(selector string, options model.Iterator) *MongoRefController
type MultiViewsListModel ¶
type MultiViewsListModel []Views
func (MultiViewsListModel) ItemView ¶
func (self MultiViewsListModel) ItemView(index int, ctx *Context) (view View, err error)
func (MultiViewsListModel) NumItems ¶
func (self MultiViewsListModel) NumItems() int
type NotFoundView ¶
func (*NotFoundView) Render ¶
func (self *NotFoundView) Render(ctx *Context) (err error)
type OnFormSubmitFunc ¶
type OnFormSubmitFunc func(form *Form, formModel interface{}, ctx *Context) (message string, redirect URL, err error)
func OnFormSubmit ¶
func OnFormSubmit(onSubmitFunc interface{}) OnFormSubmitFunc
OnFormSubmit wraps onSubmitFunc as a OnFormSubmitFunc with the arguments and results of OnFormSubmitFunc optional for onSubmitFunc. The order of the arguments and results is also free to choose.
type Page ¶
type Page struct { Template // Called before any other function when rendering the page OnPreRender func(page *Page, ctx *Context) (err error) // Writes the head title tag Title Renderer // Writes the head meta description tag MetaDescription Renderer // Content of the head meta viewport tag, // Config.Page.DefaultMetaViewport will be used if "" MetaViewport string // Write additional HTML head content AdditionalHead Renderer // Write head content before the stylesheet link PreCSS Renderer // stylesheet link URL CSS URL // Write head content after the stylesheet link PostCSS Renderer // Write scripts as last element of the HTML head HeadScripts Renderer // HTML body content. Will be wrapped by a div with class="container" Content View // Write scripts after body content Scripts Renderer // That way of linking to favicons my be removed in the future: Favicon16x16URL string Favicon57x57URL string Favicon72x72URL string Favicon114x114URL string Favicon129x129URL string // contains filtered or unexported fields }
Page is the basis to render complete HTML pages. An arbitrary View or ViewWithURL can be used to render other text formats like CSS or JSON.
A HTML5 Boilerplate template is used by default. See:
- gostart/templates/html5boilerplate.html
- gostart/static/css/html5boilerplate/normalize.css
- gostart/static/css/html5boilerplate/poststyle.css
Note: In the current version Mustache is always used as templates system. This will be changed to the Go v1 template system in the Go v1 syntax release.
Most HTML head and script specific text is written by Renderer functions that receive the request context as an argument. That way the content can be created dynamically.
Wrapper functions for static content are provided for convenience. See functions under Renderer below.
Example:
&Page{WriteTitle: func(response *Response, writer io.Writer) (err error) { writer.Write([]byte("Could be a dynamic title")) return nil }} &Page{WriteTitle: PageTitle("Static Title")}
To avoid reading the same data multiple times from the database in Renderer or dynamic views in the content structure, OnPreRender can be used to query and set page wide data only once at the request context.Data.
Example:
&Page{ OnPreRender: func(page *Page, ctx *Context) (err error) { context.Data = &MyPerPageData{SomeText: "Hello World!"} }, Content: DynamicView( func(ctx *Context) (view View, err error) { myPerPageData := context.Data.(*MyPerPageData) return HTML(myPerPageData.SomeText), nil }, ), }
func (*Page) IterateChildren ¶
func (self *Page) IterateChildren(callback IterateChildrenCallback)
func (*Page) LinkContent ¶
Implements the LinkModel interface
type PageConfiguration ¶
type PageConfiguration struct { Template string DefaultAdditionalHead Renderer // will be called after WriteTitle DefaultCSS string DefaultMetaViewport string DefaultHeadScripts Renderer // write scripts as last element of the HTML head DefaultScripts Renderer // will be called if Page.WriteScripts is nil PostScripts Renderer // will always be called after Page.WriteScripts DefaultAuth Authenticator // Will be used for pages with Page.NeedsAuth == true }
type Paragraph ¶
type Paragraph struct { ViewBaseWithId Class string Content View }
func (*Paragraph) IterateChildren ¶
func (self *Paragraph) IterateChildren(callback IterateChildrenCallback)
type PermanentRedirect ¶
type PermanentRedirect string
func (PermanentRedirect) Error ¶
func (self PermanentRedirect) Error() string
type RedirectView ¶
If rendered, this view will cause a HTTP redirect.
func (*RedirectView) Render ¶
func (self *RedirectView) Render(ctx *Context) (err error)
type RenderView ¶
RenderView implements all View methods for a View.Render compatible function.
Example:
renderView := RenderView( func(ctx *Context) error { writer.Write([]byte("<html><body>Any Content</body></html>")) return nil }, )
func RenderViewBindURLArgs ¶
func RenderViewBindURLArgs(renderFunc interface{}) RenderView
RenderViewBindURLArgs creates a View where renderFunc is called from View.Render with Context.URLArgs converted to function arguments. The first renderFunc argument can be of type *Context, but this is optional. All further arguments will be converted from the corresponding Context.URLArgs string to their actual type. Conversion to integer, float, string and bool arguments are supported. If there are more URLArgs than function args, then supernumerous URLArgs will be ignored. If there are less URLArgs than function args, then the function args will receive their types zero value. The result of renderFunc can be empty or of type error.
Example:
view.RenderViewBindURLArgs(func(i int, b bool) { ctx.Response.Printf("ctx.URLArgs[0]: %d, ctx.URLArgs[1]: %b", i, b) })
func (RenderView) ID ¶
func (self RenderView) ID() string
func (RenderView) Init ¶
func (self RenderView) Init(thisView View)
func (RenderView) IterateChildren ¶
func (self RenderView) IterateChildren(callback IterateChildrenCallback)
func (RenderView) Render ¶
func (self RenderView) Render(ctx *Context) error
type Renderer ¶
func FilterPortRenderer ¶
FilterPortRenderer calls renderer.Render only if the request is made to a specific port
func IndirectRenderer ¶
IndirectRenderer takes the pointer to a Renderer variable and dereferences it when the returned Renderer's Render method is called. Used to break dependency cycles of variable initializations by using a pointer to a variable instead of its value.
func NonProductionServerRenderer ¶
NotProductionServerRenderer returns renderer if view.Config.IsProductionServer is false, else nil which is a valid value for a Renderer.
func ProductionServerRenderer ¶
ProductionServerRenderer returns renderer if view.Config.IsProductionServer is true, else nil which is a valid value for a Renderer.
type Request ¶
type Request struct { *http.Request Params map[string]string // contains filtered or unexported fields }
func (*Request) AddProtocolAndHostToURL ¶
AddProtocolAndHostToURL adds the protocol (http:// or https://) and request host (domain or IP) to an URL if not present.
func (*Request) ParseUserAgent ¶
func (self *Request) ParseUserAgent() (renderer string, version utils.VersionTuple, err error)
todo: all browsers
type Response ¶
type Response struct { Session *Session // XML allowes the Response to be used as utils.XMLWriter XML *utils.XMLWriter // contains filtered or unexported fields }
func (*Response) AuthorizationRequired401 ¶
func (self *Response) AuthorizationRequired401()
func (*Response) ContentDispositionAttachment ¶
ContentDispositionAttachment makes the webbrowser open a "Save As.." dialog for the response.
func (*Response) Forbidden403 ¶
func (*Response) NotFound404 ¶
func (*Response) NotModified304 ¶
func (self *Response) NotModified304()
func (*Response) PopBody ¶
PopBody pops the buffer of the response body from the stack and returns its content.
func (*Response) PopBodyString ¶
PopBodyString pops the buffer of the response body from the stack and returns its content as string.
func (*Response) PushBody ¶
func (self *Response) PushBody()
PushBody pushes the buffer of the response body on a stack and sets a new empty buffer. This can be used to render intermediate text results. Note: Only the response body is pushed, all other state changes like setting headers will affect the final response.
func (*Response) RedirectPermanently301 ¶
func (*Response) RedirectTemporary302 ¶
func (*Response) RequireHeadScript ¶
RequireHeadScript adds dynamic JavaScript to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular head-scripts of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func (*Response) RequireHeadScriptURL ¶
RequireHeadScriptURL adds a dynamic JavaScript link to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular head-scripts of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func (*Response) RequireScript ¶
RequireScript adds dynamic JavaScript to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular scripts near the end of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func (*Response) RequireScriptURL ¶
RequireScriptURL adds a dynamic JavaScript link to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular scripts near the end of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func (*Response) RequireStyle ¶
RequireStyle adds dynamic CSS content to the page. Multiple dynamic entries will be sorted by priority. Dynamic CSS will be inserted after the regular CSS of the page.
Use this feature to dynamically add CSS to the page if the HTML content requires it.
func (*Response) RequireStyleURL ¶
RequireStyleURL adds a dynamic CSS link to the page. Multiple dynamic entries will be sorted by priority. Dynamic CSS will be inserted after the regular CSS of the page.
Use this feature to dynamically add CSS to the page if the HTML content requires it.
func (*Response) SetContentTypeByExt ¶
func (*Response) SetSecureCookie ¶
type Select ¶
type Select struct { ViewBaseWithId Model SelectModel Name string Size int // 0 shows all items, 1 shows a dropdownbox, other values show size items Class string Disabled bool }
func (*Select) IterateChildren ¶
func (self *Select) IterateChildren(callback IterateChildrenCallback)
type SelectModel ¶
type Session ¶
type Session struct { Tracker SessionTracker DataStore SessionDataStore Ctx *Context /* Cached user object of the session. User won't be set automatically, use user.OfSession(context) instead. Example for setting it automatically for every request: import "github.com/ungerik/go-start/user" Config.OnPreAuth = func(ctx *Context) error { user.OfSession(context) // Sets context.User return nil } */ User interface{} // contains filtered or unexported fields }
func (*Session) DeleteData ¶
DeleteSessionData deletes all session data.
func (*Session) ID ¶
ID returns the id of the session and if there is a session active. It's valid to call this method on a nil pointer.
type SessionDataStore ¶
type SessionDataStore interface { Get(ctx *Context, data interface{}) (ok bool, err error) Set(ctx *Context, data interface{}) (err error) Delete(ctx *Context) (err error) }
func NewCookieSessionDataStore ¶
func NewCookieSessionDataStore() SessionDataStore
type SessionTracker ¶
type SetModelValueControllerBase ¶
type SetModelValueControllerBase struct{}
type ShortTag ¶
ShortTag represents an arbitrary HTML element. It has a smaller footprint than Tag.
func (*ShortTag) IterateChildren ¶
func (self *ShortTag) IterateChildren(callback IterateChildrenCallback)
type Span ¶
type Span struct { ViewBaseWithId Class string Content View }
Span represents a HTML span element.
func (*Span) IterateChildren ¶
func (self *Span) IterateChildren(callback IterateChildrenCallback)
type StandardFormLayout ¶
StandardFormLayout.
CSS needed for StandardFormLayout:
form label:after { content: ":"; } form input[type=checkbox] + label:after { content: ""; }
Additional CSS for labels above input fields (except checkboxes):
form label { display: block; } form input[type=checkbox] + label { display: inline; }
DIV classes for coloring:
form .required {} form .error {} form .success {}
func (*StandardFormLayout) BeginFormContent ¶
func (self *StandardFormLayout) BeginFormContent(form *Form, ctx *Context, formContent *Views) error
func (*StandardFormLayout) BeginIndexedFields ¶
func (*StandardFormLayout) BeginNamedFields ¶
func (*StandardFormLayout) EndFormContent ¶
func (*StandardFormLayout) EndIndexedFields ¶
func (*StandardFormLayout) EndNamedFields ¶
func (*StandardFormLayout) GetDefaultInputSize ¶
func (self *StandardFormLayout) GetDefaultInputSize(metaData *model.MetaData) int
func (*StandardFormLayout) IndexedField ¶
func (*StandardFormLayout) NamedField ¶
func (*StandardFormLayout) NewAddButton ¶
func (self *StandardFormLayout) NewAddButton(onclick string, form *Form) View
func (*StandardFormLayout) NewDownButton ¶
func (self *StandardFormLayout) NewDownButton(disabled bool, onclick string, form *Form) View
func (*StandardFormLayout) NewFieldDescrtiption ¶
func (self *StandardFormLayout) NewFieldDescrtiption(description string, form *Form) View
func (*StandardFormLayout) NewFieldErrorMessage ¶
func (*StandardFormLayout) NewGeneralErrorMessage ¶
func (self *StandardFormLayout) NewGeneralErrorMessage(message string, form *Form) View
func (*StandardFormLayout) NewHiddenInput ¶
func (*StandardFormLayout) NewRemoveButton ¶
func (self *StandardFormLayout) NewRemoveButton(onclick string, form *Form) View
func (*StandardFormLayout) NewSubmitButton ¶
func (self *StandardFormLayout) NewSubmitButton(text, confirmationMessage string, form *Form) View
func (*StandardFormLayout) NewSuccessMessage ¶
func (self *StandardFormLayout) NewSuccessMessage(message string, form *Form) View
func (*StandardFormLayout) NewTableHeader ¶
func (*StandardFormLayout) NewUpButton ¶
func (self *StandardFormLayout) NewUpButton(disabled bool, onclick string, form *Form) View
func (*StandardFormLayout) SubmitError ¶
func (*StandardFormLayout) SubmitSuccess ¶
type StaticFile ¶
type StaticFile struct { ViewBase Filename string // Will set file extension at ContentType ContentTypeExt string // contains filtered or unexported fields }
func (*StaticFile) Render ¶
func (self *StaticFile) Render(ctx *Context) (err error)
type StringLink ¶
type StringLink struct { Url string Content View // If nil, then self.LinkTitle() will be used Title string // If "", then self.URL will be used Rel string }
StringLink implements the LinkModel interface with string values for Url, Title, and Rel.
func (*StringLink) LinkContent ¶
func (self *StringLink) LinkContent(ctx *Context) View
func (*StringLink) LinkRel ¶
func (self *StringLink) LinkRel(ctx *Context) string
func (*StringLink) LinkTitle ¶
func (self *StringLink) LinkTitle(ctx *Context) string
func (*StringLink) URL ¶
func (self *StringLink) URL(ctx *Context) string
type StringsSelectModel ¶
func (*StringsSelectModel) Disabled ¶
func (self *StringsSelectModel) Disabled(index int) bool
func (*StringsSelectModel) IterateChildren ¶
func (self *StringsSelectModel) IterateChildren(parent *Select, callback func(parent View, child View) (next bool))
func (*StringsSelectModel) NumOptions ¶
func (self *StringsSelectModel) NumOptions() int
func (*StringsSelectModel) RenderItem ¶
func (self *StringsSelectModel) RenderItem(index int, ctx *Context) (err error)
func (*StringsSelectModel) Selected ¶
func (self *StringsSelectModel) Selected(index int) bool
func (*StringsSelectModel) Value ¶
func (self *StringsSelectModel) Value(index int) string
type SubmitButton ¶
type SubmitButton struct { ViewBaseWithId Name string Value interface{} Class string Disabled bool TabIndex int OnClick string OnClickConfirm string // Will add a confirmation dialog for onclick }
func (*SubmitButton) Render ¶
func (self *SubmitButton) Render(ctx *Context) (err error)
type Table ¶
type Table struct { ViewBaseWithId Model TableModel Class string Caption string HeaderRow bool }
type TableModel ¶
type Tag ¶
type Tag struct { ViewBaseWithId Tag string Content View Class string Attribs map[string]string ExtraClose bool }
Tag represents an arbitrary HTML element.
func (*Tag) IterateChildren ¶
func (self *Tag) IterateChildren(callback IterateChildrenCallback)
type Template ¶
type Template struct { ViewBase Filename string // Will set file extension at ContentType Text string ContentTypeExt string GetContext GetTemplateContextFunc TemplateSystem templatesystem.Implementation // If nil, self.App.Config.TemplateSystem is used // contains filtered or unexported fields }
func NewTemplate ¶
func NewTemplate(filename string, getContext GetTemplateContextFunc) *Template
type TextArea ¶
type TextField ¶
type TextFieldType ¶
type TextFieldType int
const ( NormalTextField TextFieldType = iota PasswordTextField EmailTextField )
type TextPreview ¶
type TextPreview struct { ViewBase PlainText string MaxLength int ShortLength int // Shortened length if len(Text) > MaxLength. If zero, MaxLength will be used MoreLink LinkModel }
func (*TextPreview) Render ¶
func (self *TextPreview) Render(ctx *Context) (err error)
type URL ¶
URL is an interface to return URL strings depending on the request path args.
func IndirectURL ¶
func IndirectURL(urlPtr interface{}) URL
IndirectURL encapsulates pointers to URL implementations. To break circular dependencies, addresses of URL implementing variables can be passed to this function that encapsulates it with an URL implementation that dereferences the pointers at runtime.
type URLLink ¶
type URLLink struct { Url URL Content View // If is nil, then self.LinkTitle() will be used Title string // If is "", then self.URL will be used Rel string }
URLLink implements the LinkModel interface with a reference to a URL and string values for Title and Rel.
func (*URLLink) LinkContent ¶
type URLWithArgs ¶
URLWithArgs binds Args to an URL. Url.URL() will be called with response.URLArgs(Args...)
func NewURLWithArgs ¶
func NewURLWithArgs(url URL, args ...string) *URLWithArgs
func (*URLWithArgs) URL ¶
func (self *URLWithArgs) URL(ctx *Context) string
type Video ¶
type Video struct { ViewBaseWithId Class string URL string Width int Height int }
Video shows a Youtube Video, other formats to come.
type View ¶
type View interface { Init(thisView View) ID() string IterateChildren(callback IterateChildrenCallback) // Everything written to out will be discarded if there was an error // out.Write() is not expected to return errors like bytes.Buffer Render(ctx *Context) (err error) }
View is the basic interface for all types in the view package. A view can have an id, child views and renders its content to a XMLWriter. nil is permitted as View value and will be ignored while rendering HTML.
func JQueryUIAutocomplete ¶
func NewView ¶
func NewView(content interface{}) View
Encapsulates content as View. Strings or fmt.Stringer implementations will be HTML escaped. View implementations will be passed through.
func NonProductionServerView ¶
NotProductionServerView returns view if view.Config.IsProductionServer is false, else nil which is a valid value for a View.
func ProductionServerView ¶
ProductionServerView returns view if view.Config.IsProductionServer is true, else nil which is a valid value for a View.
func RequireHeadScript ¶
RequireHeadScript adds dynamic JavaScript to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular head-scripts of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func RequireHeadScriptURL ¶
RequireHeadScriptURL adds a dynamic JavaScript link to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular head-scripts of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func RequireScript ¶
RequireScript adds dynamic JavaScript to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular scripts near the end of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func RequireScriptURL ¶
RequireScriptURL adds a dynamic JavaScript link to the page. Multiple dynamic entries will be sorted by priority. The dynamic JavaScript will be inserted after the regular scripts near the end of the page.
Use this feature to dynamically add JavaScript to the page if the HTML content requires it.
func RequireStyle ¶
RequireStyle adds dynamic CSS content to the page. Multiple dynamic entries will be sorted by priority. Dynamic CSS will be inserted after the regular CSS of the page.
Use this feature to dynamically add CSS to the page if the HTML content requires it.
func RequireStyleURL ¶
RequireStyleURL adds a dynamic CSS link to the page. Multiple dynamic entries will be sorted by priority. Dynamic CSS will be inserted after the regular CSS of the page.
Use this feature to dynamically add CSS to the page if the HTML content requires it.
func UncacheView ¶
func UncacheView(cachedView *CachedView) View
UncacheView removes the CachedView from the internal list CachedViews that is used by ClearAllCaches(). It returnes the View wrapped CachedView.
func WrapContents ¶
func WrapContents(contents ...interface{}) View
Encapsulates multiple content arguments as View by calling NewView() for every one of them. It is more efficient for one view because the view is passed through instead of wrapped with a Views slice like NewViews does.
type ViewBase ¶
type ViewBase struct {
// contains filtered or unexported fields
}
ViewBase is a base for View implementations.
func (*ViewBase) IterateChildren ¶
func (self *ViewBase) IterateChildren(callback IterateChildrenCallback)
type ViewBaseWithId ¶
type ViewBaseWithId struct { ViewBase // contains filtered or unexported fields }
ViewBaseWithId extends ViewBase with an id for the view.
func (*ViewBaseWithId) ID ¶
func (self *ViewBaseWithId) ID() string
func (*ViewBaseWithId) Init ¶
func (self *ViewBaseWithId) Init(thisView View)
type ViewPath ¶
type ViewPath struct { Name string Args int View View Auth Authenticator NoAuth URL Sub []ViewPath // Only allowed when View is a Page or nil }
ViewPath holds all data necessary to define the URL path of a view, including the number of arguments parsed from the URL path, an Authenticator and sub paths.
type ViewURLWrapper ¶
type ViewURLWrapper struct { View View // contains filtered or unexported fields }
func NewViewURLWrapper ¶
func NewViewURLWrapper(view View) *ViewURLWrapper
func (*ViewURLWrapper) ID ¶
func (self *ViewURLWrapper) ID() string
func (*ViewURLWrapper) Init ¶
func (self *ViewURLWrapper) Init(thisView View)
func (*ViewURLWrapper) IterateChildren ¶
func (self *ViewURLWrapper) IterateChildren(callback IterateChildrenCallback)
func (*ViewURLWrapper) Render ¶
func (self *ViewURLWrapper) Render(ctx *Context) (err error)
func (*ViewURLWrapper) SetPath ¶
func (self *ViewURLWrapper) SetPath(path string)
func (*ViewURLWrapper) URL ¶
func (self *ViewURLWrapper) URL(ctx *Context) string
type ViewWithURL ¶
ViewWithURL combines the View interface with the URL interface for views that have an URL
func IndirectViewWithURL ¶
func IndirectViewWithURL(viewWithURL *ViewWithURL) ViewWithURL
type Views ¶
type Views []View
Views implements the View interface for a slice of views. The views of the slice are the child views.
func AddStandardLabel ¶
func NewHTML5BoilerplateCSSTemplate ¶
func NewHTML5BoilerplateCSSTemplate(getContext GetTemplateContextFunc, filenames ...string) Views
func NewViews ¶
func NewViews(contents ...interface{}) Views
Encapsulates multiple content arguments as views by calling NewView() for every one of them.
func (Views) IterateChildren ¶
func (self Views) IterateChildren(callback IterateChildrenCallback)
Does not iterate nil children
type ViewsListModel ¶
type ViewsListModel []View
func (ViewsListModel) ItemView ¶
func (self ViewsListModel) ItemView(index int, ctx *Context) (view View, err error)
func (ViewsListModel) NumItems ¶
func (self ViewsListModel) NumItems() int
type ViewsTableModel ¶
type ViewsTableModel []Views
func (ViewsTableModel) Columns ¶
func (self ViewsTableModel) Columns() int
func (ViewsTableModel) Rows ¶
func (self ViewsTableModel) Rows() int
Source Files ¶
- aside.go
- authenticator.go
- basicauth.go
- button.go
- cachedview.go
- canvas.go
- checkbox.go
- comment.go
- config.go
- contactform.go
- context.go
- csrfprotector.go
- div.go
- doc.go
- dummyimage.go
- dummytext.go
- dynamicview.go
- errors.go
- fileinput.go
- form.go
- format.go
- formfieldcontrollers.go
- formlayout.go
- frontcontroller.go
- functions.go
- google.go
- hiddeninput.go
- html.go
- if.go
- iframe.go
- image.go
- indirecturl.go
- indirectviewwithurl.go
- jquery.go
- label.go
- labeledmodelview.go
- link.go
- linkmodel.go
- list.go
- menu.go
- middleware.go
- modaldialog.go
- modeliteratortableview.go
- modeliteratorview.go
- notfoundview.go
- page.go
- pagelink.go
- pagevar.go
- paragraph.go
- redirectview.go
- renderer.go
- renderview.go
- request.go
- require.go
- response.go
- select.go
- session.go
- sessiondatastore.go
- sessiontracker.go
- shortcuts.go
- shorttag.go
- span.go
- standardformlayout.go
- staticfile.go
- stringlink.go
- stringurl.go
- submitbutton.go
- table.go
- tag.go
- template.go
- textarea.go
- textfield.go
- textpreview.go
- url.go
- urllink.go
- urlwithargs.go
- video.go
- view.go
- viewbase.go
- viewbasewithid.go
- viewpath.go
- views.go
- viewurlwrapper.go
- viewwithurl.go