view

package
v0.0.0-...-9e0c27b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 9, 2012 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

The View of MVC.

Index

Constants

View Source
const (
	TextAreaDefaultCols = 80
	TextAreaDefaultRows = 3
)
View Source
const FormIDName = "gostart_form_id"
View Source
const LoremIpsum = "" /* 3101-byte string literal not displayed */
View Source
const ModalDialogCloseScript = "Avgrund.hide();"
View Source
const MultipartFormData = "multipart/form-data"
View Source
const PathFragmentPattern = "([a-zA-Z0-9_\\-\\.]+)"

Variables

View Source
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),
}
View Source
var StructTagKey = "view"

Functions

func ClearAllCaches

func ClearAllCaches()

ClearAllCaches cals ClearCache() for all CachedView objects created with CacheView().

func DecryptCookie

func DecryptCookie(data []byte) (result []byte, err error)

func EncryptCookie

func EncryptCookie(data []byte) (result []byte, err error)

func FindStaticFile

func FindStaticFile(filename string) (filePath string, found bool, modifiedTime int64)

func FindTemplateFile

func FindTemplateFile(filename string) (filePath string, found bool, modifiedTime int64)

func GetFileUploadFormModel

func GetFileUploadFormModel(form *Form, ctx *Context) (interface{}, error)

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 NewViewID

func NewViewID(view View) (id string)

func RenderChildViewsHTML

func RenderChildViewsHTML(parent View, ctx *Context) (err error)

func RenderTemplate

func RenderTemplate(filename string, out io.Writer, context interface{}) (err error)

func RenderTemplateString

func RenderTemplateString(tmplString string, name string, out io.Writer, context interface{}) (err error)

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

func RunServerAddr(addr string, paths *ViewPath)

RunServerAddr starts a webserver with the given paths and address. If paths is nil, only static files will be served.

func TableHeaderRow

func TableHeaderRow(views ...View) func(ctx *Context) (Views, error)

func TableHeaderRowEscape

func TableHeaderRowEscape(s ...string) func(ctx *Context) (Views, error)

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)

func (*Aside) Render

func (self *Aside) Render(ctx *Context) (err error)

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

type BasicAuth struct {
	Realm        string
	UserPassword map[string]string
}

BasicAuth implements HTTP basic auth as Authenticator.

func NewBasicAuth

func NewBasicAuth(realm string, username string, password string) *BasicAuth

NewBasicAuth creates a BasicAuth instance with a single username and password.

func (*BasicAuth) Authenticate

func (self *BasicAuth) Authenticate(ctx *Context) (ok bool, err error)

type BoolAuth

type BoolAuth bool

BoolAuth always returns its value at Authenticate(). Can be used for debugging.

func (BoolAuth) Authenticate

func (self BoolAuth) Authenticate(ctx *Context) (ok bool, err error)

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 ModalDialogCloseButton(text string) *Button

func (*Button) IterateChildren

func (self *Button) IterateChildren(callback IterateChildrenCallback)

func (*Button) Render

func (self *Button) Render(ctx *Context) (err error)

type CSRFProtector

type CSRFProtector interface {
	ExtraFormField() View
	Validate(ctx *Context) (ok bool, err error)
}

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 Canvas

type Canvas struct {
	ViewBaseWithId
	Class  string
	Width  int
	Height int
}

func CANVAS

func CANVAS(class string, width, height int) *Canvas

func (*Canvas) Render

func (self *Canvas) Render(ctx *Context) (err error)

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.

func (*Checkbox) Render

func (self *Checkbox) Render(ctx *Context) (err error)

type Comment

type Comment string

func (Comment) ID

func (self Comment) ID() string

func (Comment) Init

func (self Comment) Init(thisView View)

func (Comment) IterateChildren

func (self Comment) IterateChildren(callback IterateChildrenCallback)

func (Comment) Render

func (self Comment) Render(ctx *Context) (err error)

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

func (self *Context) ForURLArgs(urlArgs ...string) *Context

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

func (self *Context) ForURLArgsConvert(urlArgs ...interface{}) *Context

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

func DIV(class string, content ...interface{}) *Div

Creates a Div object with a HTML class attribute and optional content.

func (*Div) IterateChildren

func (self *Div) IterateChildren(callback IterateChildrenCallback)

func (*Div) Render

func (self *Div) Render(ctx *Context) (err error)

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

type DynamicView func(ctx *Context) (view View, err error)

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) CellView

func (self EscapeStringsTableModel) CellView(row int, column int, ctx *Context) (view View, err error)

func (EscapeStringsTableModel) Columns

func (self EscapeStringsTableModel) Columns() int

func (EscapeStringsTableModel) Rows

func (self EscapeStringsTableModel) Rows() int

type FileInput

type FileInput struct {
	ViewBaseWithId
	Class    string
	Name     string
	Disabled bool
}

func (*FileInput) Render

func (self *FileInput) Render(ctx *Context) (err error)

type FileUploadFormModel

type FileUploadFormModel struct {
	File model.File
}

type Forbidden

type Forbidden string

func (Forbidden) Error

func (self Forbidden) Error() string

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

func NewContactForm(recipientEmail, subjectPrefix, formClass, buttonClass, formID string) *Form

NewContactForm creates a new contact form that sends submitted data to recipientEmail.

func (*Form) AddMongoRefController

func (self *Form) AddMongoRefController(selector string, options model.Iterator)

func (*Form) DirectFieldLabel

func (self *Form) DirectFieldLabel(metaData *model.MetaData) string

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) FieldInputClass

func (self *Form) FieldInputClass(metaData *model.MetaData) string

func (*Form) FieldLabel

func (self *Form) FieldLabel(metaData *model.MetaData) string

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 (self *Form) GetErrorMessageClass() string

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 (self *Form) GetFieldDescription(metaData *model.MetaData) string

func (*Form) GetFieldDescriptionClass

func (self *Form) GetFieldDescriptionClass() string

func (*Form) GetInputSize

func (self *Form) GetInputSize(metaData *model.MetaData) int

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 (self *Form) GetRequiredMarker() View

func (*Form) GetSubmitButtonClass

func (self *Form) GetSubmitButtonClass() string

func (*Form) GetSubmitButtonText

func (self *Form) GetSubmitButtonText() string

Returns self.SubmitButtonText if not empty, else Config.Form.DefaultSubmitButtonText

func (*Form) GetSuccessMessageClass

func (self *Form) GetSuccessMessageClass() string

func (*Form) InputFieldPlaceholder

func (self *Form) InputFieldPlaceholder(metaData *model.MetaData) string

func (*Form) IsFieldDisabled

func (self *Form) IsFieldDisabled(field *model.MetaData) bool

func (*Form) IsFieldExcluded

func (self *Form) IsFieldExcluded(field *model.MetaData, ctx *Context) bool

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

func (self *Form) IsFieldHidden(field *model.MetaData) bool

IsFieldHidden returns if a hidden input element will be created for a form field. Hidden fields are not validated.

func (*Form) IsFieldRequired

func (self *Form) IsFieldRequired(field *model.MetaData) bool

func (*Form) IsFieldVisible

func (self *Form) IsFieldVisible(field *model.MetaData, ctx *Context) bool

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.

func (*Form) IsPost

func (self *Form) IsPost(request *Request) bool

func (*Form) Render

func (self *Form) Render(ctx *Context) (err error)

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 (FormFieldControllers) NewInput

func (self FormFieldControllers) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (FormFieldControllers) SetValue

func (self FormFieldControllers) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

func (FormFieldControllers) Supports

func (self FormFieldControllers) Supports(metaData *model.MetaData, form *Form) bool

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 Format

type Format struct {
	ViewBase
	Text   string
	Args   []interface{}
	Escape bool
}

func (*Format) Render

func (self *Format) Render(ctx *Context) (err error)

type FrontController

type FrontController func(content View) ViewWithURL

func (FrontController) ContentFunc

func (self FrontController) ContentFunc(contentFunc interface{}) ViewWithURL

type GetFormModelFunc

type GetFormModelFunc func(form *Form, ctx *Context) (model interface{}, err error)

func FormModel

func FormModel(model interface{}) GetFormModelFunc

type GetModelIteratorFunc

type GetModelIteratorFunc func(ctx *Context) model.Iterator

func ModelIterator

func ModelIterator(iter model.Iterator) GetModelIteratorFunc

type GetModelIteratorViewFunc

type GetModelIteratorViewFunc func(ctx *Context, model interface{}) (view View, err error)

type GetTemplateContextFunc

type GetTemplateContextFunc func(ctx *Context) (context interface{}, err error)

func TemplateContext

func TemplateContext(context interface{}) GetTemplateContextFunc

type HTML

type HTML string
var (
	JQuery   HTML = `` /* 187-byte string literal not displayed */
	JQueryUI HTML = `` /* 207-byte string literal not displayed */
)

func BR

func BR() HTML

func DivClearBoth

func DivClearBoth() HTML

func DummyText

func DummyText(length int) HTML

DummyText return a HTML object with lorem ipsum text the passed length.

func Escape

func Escape(text string) HTML

Escape HTML escapes a string.

func GoogleAnalytics

func GoogleAnalytics(trackingID string) HTML

func GoogleMaps

func GoogleMaps(apiKey string, sensor bool, callback string) HTML

todo: replace http with https if necessary

func HR

func HR() HTML

func Printf

func Printf(text string, args ...interface{}) HTML

Printf creates an unescaped HTML string.

func PrintfEscape

func PrintfEscape(text string, args ...interface{}) HTML

PrintfEscape creates an escaped HTML string.

func SCRIPT

func SCRIPT(script string) HTML

func STYLE

func STYLE(css string) HTML
func ScriptLink(url string) HTML
func StylesheetLink(url string) HTML

func (HTML) ID

func (self HTML) ID() string

func (HTML) Init

func (self HTML) Init(thisView View)

func (HTML) IterateChildren

func (self HTML) IterateChildren(callback IterateChildrenCallback)

func (HTML) Render

func (self HTML) Render(ctx *Context) (err error)

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) CellView

func (self HTMLStringsTableModel) CellView(row int, column int, ctx *Context) (view View, err error)

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) Init

func (self *If) Init(thisView View)

func (*If) IterateChildren

func (self *If) IterateChildren(callback IterateChildrenCallback)

func (*If) Render

func (self *If) Render(ctx *Context) (err error)

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

func GoogleMapsIframe(width, height int, location string) *Iframe

func (*Iframe) Render

func (self *Iframe) Render(ctx *Context) (err error)

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
}

func IMG

func IMG(url string, dimensions ...int) *Image

Img creates a HTML img element for an URL with optional width and height. The first int of dimensions is width, the second one height.

func (*Image) Render

func (self *Image) Render(ctx *Context) (err error)

type IndexedStringsSelectModel

type IndexedStringsSelectModel struct {
	Options []string
	Index   int
}

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 IterateChildrenCallback func(parent View, child View) (next bool)

type JQueryDialog

type JQueryDialog struct {
	Div
	Title     string
	AutoOpen  bool
	CloseText string
}

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 Label

type Label struct {
	ViewBaseWithId
	Class   string
	For     View
	Content View
}

func (*Label) Render

func (self *Label) 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 struct {
	ViewBaseWithId
	Class     string
	Model     LinkModel
	NewWindow bool
}

func A

func A(url interface{}, content ...interface{}) *Link

A creates a HTML link.

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.

func (*Link) Render

func (self *Link) Render(ctx *Context) (err error)

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

func NewLinkModelRel(url interface{}, rel string, content ...interface{}) LinkModel

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.

func UL

func UL(items ...interface{}) *List

Ul is a shortcut to create an unordered list by wrapping items as HTML views. NewView will be called for every passed item.

func (*List) Render

func (self *List) Render(ctx *Context) (err error)

type ListModel

type ListModel interface {
	NumItems() int
	ItemView(index int, ctx *Context) (view View, err error)
}
type Menu struct {
	ViewBaseWithId
	Class           string
	ItemClass       string
	ActiveItemClass string
	BetweenItems    string
	Items           []LinkModel
	Reverse         bool
}
func (self *Menu) Render(ctx *Context) (err error)

type Middleware

type Middleware interface {
	PreRender(ctx *Context) (abort bool)
	PostRender(response *Response, html string, err error) (newHtml string, newErr error)
}

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{}

func (ModelBlobController) NewInput

func (self ModelBlobController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelBlobController) SetValue

func (self ModelBlobController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

func (ModelBlobController) Supports

func (self ModelBlobController) Supports(metaData *model.MetaData, form *Form) bool

type ModelBoolController

type ModelBoolController struct{}

func (ModelBoolController) NewInput

func (self ModelBoolController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelBoolController) SetValue

func (self ModelBoolController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

func (ModelBoolController) Supports

func (self ModelBoolController) Supports(metaData *model.MetaData, form *Form) bool

type ModelChoiceController

type ModelChoiceController struct {
	SetModelValueControllerBase
}

func (ModelChoiceController) NewInput

func (self ModelChoiceController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelChoiceController) Supports

func (self ModelChoiceController) Supports(metaData *model.MetaData, form *Form) bool

type ModelDateController

type ModelDateController struct {
	SetModelValueControllerBase
}

func (ModelDateController) NewInput

func (self ModelDateController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelDateController) Supports

func (self ModelDateController) Supports(metaData *model.MetaData, form *Form) bool

type ModelDateTimeController

type ModelDateTimeController struct {
	SetModelValueControllerBase
}

func (ModelDateTimeController) NewInput

func (self ModelDateTimeController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelDateTimeController) Supports

func (self ModelDateTimeController) Supports(metaData *model.MetaData, form *Form) bool

type ModelDynamicChoiceController

type ModelDynamicChoiceController struct {
	SetModelValueControllerBase
}

func (ModelDynamicChoiceController) NewInput

func (self ModelDynamicChoiceController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelDynamicChoiceController) Supports

func (self ModelDynamicChoiceController) Supports(metaData *model.MetaData, form *Form) bool

type ModelEmailController

type ModelEmailController struct {
	SetModelValueControllerBase
}

func (ModelEmailController) NewInput

func (self ModelEmailController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelEmailController) Supports

func (self ModelEmailController) Supports(metaData *model.MetaData, form *Form) bool

type ModelFileController

type ModelFileController struct{}

func (ModelFileController) NewInput

func (self ModelFileController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelFileController) SetValue

func (self ModelFileController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

func (ModelFileController) Supports

func (self ModelFileController) Supports(metaData *model.MetaData, form *Form) bool

type ModelFloatController

type ModelFloatController struct {
	SetModelValueControllerBase
}

func (ModelFloatController) NewInput

func (self ModelFloatController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelFloatController) Supports

func (self ModelFloatController) Supports(metaData *model.MetaData, form *Form) bool

type ModelIntController

type ModelIntController struct {
	SetModelValueControllerBase
}

func (ModelIntController) NewInput

func (self ModelIntController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelIntController) Supports

func (self ModelIntController) Supports(metaData *model.MetaData, form *Form) bool

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{}

func (ModelMultipleChoiceController) NewInput

func (self ModelMultipleChoiceController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelMultipleChoiceController) SetValue

func (self ModelMultipleChoiceController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

func (ModelMultipleChoiceController) Supports

func (self ModelMultipleChoiceController) Supports(metaData *model.MetaData, form *Form) bool

type ModelPasswordController

type ModelPasswordController struct {
	SetModelValueControllerBase
}

func (ModelPasswordController) NewInput

func (self ModelPasswordController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelPasswordController) Supports

func (self ModelPasswordController) Supports(metaData *model.MetaData, form *Form) bool

type ModelPhoneController

type ModelPhoneController struct {
	SetModelValueControllerBase
}

func (ModelPhoneController) NewInput

func (self ModelPhoneController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelPhoneController) Supports

func (self ModelPhoneController) Supports(metaData *model.MetaData, form *Form) bool

type ModelStringController

type ModelStringController struct {
	SetModelValueControllerBase
}

func (ModelStringController) NewInput

func (self ModelStringController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelStringController) Supports

func (self ModelStringController) Supports(metaData *model.MetaData, form *Form) bool

type ModelTextController

type ModelTextController struct {
	SetModelValueControllerBase
}

func (ModelTextController) NewInput

func (self ModelTextController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelTextController) Supports

func (self ModelTextController) Supports(metaData *model.MetaData, form *Form) bool

type ModelUrlController

type ModelUrlController struct {
	SetModelValueControllerBase
}

func (ModelUrlController) NewInput

func (self ModelUrlController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (ModelUrlController) Supports

func (self ModelUrlController) Supports(metaData *model.MetaData, form *Form) bool

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

func (*MongoRefController) NewInput

func (self *MongoRefController) NewInput(withLabel bool, metaData *model.MetaData, form *Form) (input View, err error)

func (*MongoRefController) SetValue

func (self *MongoRefController) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

func (*MongoRefController) Supports

func (self *MongoRefController) Supports(metaData *model.MetaData, form *Form) bool

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 NotFound

type NotFound string

func (NotFound) Error

func (self NotFound) Error() string

type NotFoundView

type NotFoundView struct {
	ViewBase
	Message string
}

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 OnFormValidationErrorFunc

type OnFormValidationErrorFunc func(form *Form, formModel interface{}, fieldValidationErrors, generalValidationErrors []error) (revalidate bool)

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) Init

func (self *Page) Init(thisView View)

func (*Page) IterateChildren

func (self *Page) IterateChildren(callback IterateChildrenCallback)

func (*Page) LinkContent

func (self *Page) LinkContent(ctx *Context) View

Implements the LinkModel interface

func (*Page) LinkRel

func (self *Page) LinkRel(ctx *Context) string

Implements the LinkModel interface

func (*Page) LinkTitle

func (self *Page) LinkTitle(ctx *Context) string

Implements the LinkModel interface

func (*Page) Render

func (self *Page) Render(ctx *Context) (err error)

func (*Page) SetPath

func (self *Page) SetPath(path string)

func (*Page) URL

func (self *Page) URL(ctx *Context) string

Implements the URL and 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 PageLink struct {
	Page    **Page
	Content View
	Title   string
	Rel     string
}
func NewPageLink(page **Page, title string) *PageLink

func (*PageLink) LinkContent

func (self *PageLink) LinkContent(ctx *Context) View

func (*PageLink) LinkRel

func (self *PageLink) LinkRel(ctx *Context) string

func (*PageLink) LinkTitle

func (self *PageLink) LinkTitle(ctx *Context) string

func (*PageLink) URL

func (self *PageLink) URL(ctx *Context) string

type Paragraph

type Paragraph struct {
	ViewBaseWithId
	Class   string
	Content View
}

func (*Paragraph) IterateChildren

func (self *Paragraph) IterateChildren(callback IterateChildrenCallback)

func (*Paragraph) Render

func (self *Paragraph) Render(ctx *Context) (err error)

type PermanentRedirect

type PermanentRedirect string

func (PermanentRedirect) Error

func (self PermanentRedirect) Error() string

type Redirect

type Redirect string

func (Redirect) Error

func (self Redirect) Error() string

type RedirectView

type RedirectView struct {
	ViewBase
	URL       string
	Permanent bool
}

If rendered, this view will cause a HTTP redirect.

func (*RedirectView) Render

func (self *RedirectView) Render(ctx *Context) (err error)

type Render

type Render func(ctx *Context) error

func (Render) Render

func (self Render) Render(ctx *Context) error

type RenderView

type RenderView func(ctx *Context) error

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

type Renderer interface {
	Render(ctx *Context) error
}

func FilterPortRenderer

func FilterPortRenderer(port uint16, renderer Renderer) Renderer

FilterPortRenderer calls renderer.Render only if the request is made to a specific port

func IndirectRenderer

func IndirectRenderer(rendererPtr *Renderer) Renderer

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

func NonProductionServerRenderer(renderer Renderer) Renderer

NotProductionServerRenderer returns renderer if view.Config.IsProductionServer is false, else nil which is a valid value for a Renderer.

func ProductionServerRenderer

func ProductionServerRenderer(renderer Renderer) Renderer

ProductionServerRenderer returns renderer if view.Config.IsProductionServer is true, else nil which is a valid value for a Renderer.

type Renderers

type Renderers []Renderer

func (Renderers) Render

func (self Renderers) Render(ctx *Context) error

type Request

type Request struct {
	*http.Request

	Params map[string]string
	// contains filtered or unexported fields
}

func (*Request) AddProtocolAndHostToURL

func (self *Request) AddProtocolAndHostToURL(url string) string

AddProtocolAndHostToURL adds the protocol (http:// or https://) and request host (domain or IP) to an URL if not present.

func (*Request) GetSecureCookie

func (self *Request) GetSecureCookie(name string) (string, bool)

func (*Request) ParseUserAgent

func (self *Request) ParseUserAgent() (renderer string, version utils.VersionTuple, err error)

todo: all browsers

func (*Request) Port

func (self *Request) Port() uint16

func (*Request) URLString

func (self *Request) URLString() string

URL returns the complete URL of the request including protocol and host.

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) Abort

func (self *Response) Abort(status int, body string)

func (*Response) AuthorizationRequired401

func (self *Response) AuthorizationRequired401()

func (*Response) Bytes

func (self *Response) Bytes() []byte

func (*Response) ContentDispositionAttachment

func (self *Response) ContentDispositionAttachment(filename string)

ContentDispositionAttachment makes the webbrowser open a "Save As.." dialog for the response.

func (*Response) Forbidden403

func (self *Response) Forbidden403(message string)

func (*Response) Header

func (self *Response) Header() http.Header

func (*Response) NotFound404

func (self *Response) NotFound404(message string)

func (*Response) NotModified304

func (self *Response) NotModified304()

func (*Response) PopBody

func (self *Response) PopBody() (bufferData []byte)

PopBody pops the buffer of the response body from the stack and returns its content.

func (*Response) PopBodyString

func (self *Response) PopBodyString() (bufferData string)

PopBodyString pops the buffer of the response body from the stack and returns its content as string.

func (*Response) Printf

func (self *Response) Printf(format string, args ...interface{}) (n int, err error)

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 (self *Response) RedirectPermanently301(url string)

func (*Response) RedirectTemporary302

func (self *Response) RedirectTemporary302(url string)

func (*Response) RequireHeadScript

func (self *Response) RequireHeadScript(script string, priority int)

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

func (self *Response) RequireHeadScriptURL(url string, priority int)

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

func (self *Response) RequireScript(script string, priority int)

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

func (self *Response) RequireScriptURL(url string, priority int)

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

func (self *Response) RequireStyle(css string, priority int)

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

func (self *Response) RequireStyleURL(url string, priority int)

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 (self *Response) SetContentTypeByExt(ext string)

func (*Response) SetSecureCookie

func (self *Response) SetSecureCookie(name string, val string, age int64, path string)

func (*Response) String

func (self *Response) String() string

func (*Response) Write

func (self *Response) Write(p []byte) (n int, err error)

func (*Response) WriteByte

func (self *Response) WriteByte(c byte) error

func (*Response) WriteString

func (self *Response) WriteString(s string) (n int, err error)

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)

func (*Select) Render

func (self *Select) Render(ctx *Context) (err error)

type SelectModel

type SelectModel interface {
	NumOptions() int
	Value(index int) string
	Selected(index int) bool
	Disabled(index int) bool
	RenderItem(index int, ctx *Context) (err error)
	IterateChildren(parent *Select, callback func(parent View, child View) (next bool))
}

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) Data

func (self *Session) Data(out interface{}) (ok bool, err error)

SessionData returns all session data in out.

func (*Session) DeleteData

func (self *Session) DeleteData() (err error)

DeleteSessionData deletes all session data.

func (*Session) DeleteID

func (self *Session) DeleteID()

func (*Session) ID

func (self *Session) ID() (id string, ok bool)

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.

func (*Session) SetData

func (self *Session) SetData(data interface{}) (err error)

SetSessionData sets all session data.

func (*Session) SetID

func (self *Session) SetID(id string)

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 SessionTracker interface {
	ID(ctx *Context) (id string, ok bool)
	SetID(ctx *Context, id string)
	DeleteID(ctx *Context)
}

type SetModelValueControllerBase

type SetModelValueControllerBase struct{}

func (SetModelValueControllerBase) SetValue

func (self SetModelValueControllerBase) SetValue(value string, ctx *Context, metaData *model.MetaData, form *Form) error

type ShortTag

type ShortTag struct {
	ViewBase
	Tag     string
	Class   string
	Attribs map[string]string
	Content View
}

ShortTag represents an arbitrary HTML element. It has a smaller footprint than Tag.

func (*ShortTag) IterateChildren

func (self *ShortTag) IterateChildren(callback IterateChildrenCallback)

func (*ShortTag) Render

func (self *ShortTag) Render(ctx *Context) (err error)

type Span

type Span struct {
	ViewBaseWithId
	Class   string
	Content View
}

Span represents a HTML span element.

func SPAN

func SPAN(class string, content ...interface{}) *Span

func (*Span) IterateChildren

func (self *Span) IterateChildren(callback IterateChildrenCallback)

func (*Span) Render

func (self *Span) Render(ctx *Context) (err error)

type StandardFormLayout

type StandardFormLayout struct {
	DefaultInputSize      int
	DefaultTableInputSize int
}

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 (self *StandardFormLayout) BeginIndexedFields(indexedFields *model.MetaData, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) BeginNamedFields

func (self *StandardFormLayout) BeginNamedFields(namedFields *model.MetaData, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) EndFormContent

func (self *StandardFormLayout) EndFormContent(fieldValidationErrs, generalValidationErrs []error, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) EndIndexedFields

func (self *StandardFormLayout) EndIndexedFields(indexedFields *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) EndNamedFields

func (self *StandardFormLayout) EndNamedFields(namedFields *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) GetDefaultInputSize

func (self *StandardFormLayout) GetDefaultInputSize(metaData *model.MetaData) int

func (*StandardFormLayout) IndexedField

func (self *StandardFormLayout) IndexedField(field *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) NamedField

func (self *StandardFormLayout) NamedField(field *model.MetaData, validationErr error, form *Form, ctx *Context, formContent *Views) error

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 (self *StandardFormLayout) NewFieldErrorMessage(message string, metaData *model.MetaData, form *Form) View

func (*StandardFormLayout) NewGeneralErrorMessage

func (self *StandardFormLayout) NewGeneralErrorMessage(message string, form *Form) View

func (*StandardFormLayout) NewHiddenInput

func (self *StandardFormLayout) NewHiddenInput(metaData *model.MetaData, form *Form) (View, error)

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 (self *StandardFormLayout) NewTableHeader(metaData *model.MetaData, form *Form) (View, error)

func (*StandardFormLayout) NewUpButton

func (self *StandardFormLayout) NewUpButton(disabled bool, onclick string, form *Form) View

func (*StandardFormLayout) SubmitError

func (self *StandardFormLayout) SubmitError(message string, form *Form, ctx *Context, formContent *Views) error

func (*StandardFormLayout) SubmitSuccess

func (self *StandardFormLayout) SubmitSuccess(message string, form *Form, ctx *Context, formContent *Views) error

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 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 StringURL

type StringURL string

StringURL implements the URL interface for a string.

func (StringURL) URL

func (self StringURL) URL(ctx *Context) string

type StringsSelectModel

type StringsSelectModel struct {
	Options        []string
	SelectedOption string
}

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
}

func (*Table) Render

func (self *Table) Render(ctx *Context) (err error)

type TableModel

type TableModel interface {
	Rows() int
	Columns() int
	CellView(row int, column int, ctx *Context) (view View, err error)
}

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)

func (*Tag) Render

func (self *Tag) Render(ctx *Context) (err error)

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

func (*Template) Render

func (self *Template) Render(ctx *Context) (err error)

type TextArea

type TextArea struct {
	ViewBaseWithId
	Text        string
	Name        string
	Cols        int
	Rows        int
	Readonly    bool
	Disabled    bool
	TabIndex    int
	Class       string
	Placeholder string
}

func (*TextArea) Render

func (self *TextArea) Render(ctx *Context) (err error)

type TextField

type TextField struct {
	ViewBaseWithId
	Text        string
	Name        string
	Size        int
	MaxLength   int
	Type        TextFieldType
	Readonly    bool
	Disabled    bool
	TabIndex    int
	Class       string
	Placeholder string
}

func (*TextField) Render

func (self *TextField) Render(ctx *Context) (err error)

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

type URL interface {
	URL(ctx *Context) string
}

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.

func OnFormSubmitSaveModel

func OnFormSubmitSaveModel(form *Form, formModel interface{}, ctx *Context) (msg string, url URL, err error)
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

func (self *URLLink) LinkContent(ctx *Context) View

func (*URLLink) LinkRel

func (self *URLLink) LinkRel(ctx *Context) string

func (*URLLink) LinkTitle

func (self *URLLink) LinkTitle(ctx *Context) string

func (*URLLink) URL

func (self *URLLink) URL(ctx *Context) string

type URLWithArgs

type URLWithArgs struct {
	Url  URL
	Args []string
}

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.

func (*Video) Render

func (self *Video) Render(ctx *Context) (err error)

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 ABBR

func ABBR(longTitle, abbreviation string) View

func B

func B(content ...interface{}) View

func CODE

func CODE(content ...interface{}) View

func DEL

func DEL(content ...interface{}) View

func DFN

func DFN(content ...interface{}) View

func EM

func EM(content ...interface{}) View

func H1

func H1(content ...interface{}) View

func H2

func H2(content ...interface{}) View

func H3

func H3(content ...interface{}) View

func H4

func H4(content ...interface{}) View

func H5

func H5(content ...interface{}) View

func H6

func H6(content ...interface{}) View

func I

func I(content ...interface{}) View

func JQueryUIAutocomplete

func JQueryUIAutocomplete(domSelector string, options []string, minLength int) View

func JQueryUIAutocompleteFromURL

func JQueryUIAutocompleteFromURL(domSelector string, dataURL URL, minLength int) View

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

func NonProductionServerView(view View) View

NotProductionServerView returns view if view.Config.IsProductionServer is false, else nil which is a valid value for a View.

func P

func P(content ...interface{}) View

func PRE

func PRE(content ...interface{}) View

func ProductionServerView

func ProductionServerView(view View) View

ProductionServerView returns view if view.Config.IsProductionServer is true, else nil which is a valid value for a View.

func Q

func Q(content ...interface{}) View
func RSSLink(title string, url URL) View

func RequireHeadScript

func RequireHeadScript(script string, priority int) View

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

func RequireHeadScriptURL(url string, priority int) View

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

func RequireScript(script string, priority int) View

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

func RequireScriptURL(url string, priority int) View

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

func RequireStyle(css string, priority int) View

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

func RequireStyleURL(url string, priority int) View

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 SECTION

func SECTION(class string, content ...interface{}) View

func STRONG

func STRONG(content ...interface{}) View

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) ID

func (self *ViewBase) ID() string

func (*ViewBase) Init

func (self *ViewBase) Init(thisView View)

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

type ViewWithURL interface {
	View
	URL
	SetPath(path string)
}

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 AddStandardLabel(form *Form, forView View, metaData *model.MetaData) Views

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) ID

func (self Views) ID() string

func (Views) Init

func (self Views) Init(thisView View)

func (Views) IterateChildren

func (self Views) IterateChildren(callback IterateChildrenCallback)

Does not iterate nil children

func (Views) Render

func (self Views) Render(ctx *Context) (err error)

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) CellView

func (self ViewsTableModel) CellView(row int, column int, ctx *Context) (view View, err error)

func (ViewsTableModel) Columns

func (self ViewsTableModel) Columns() int

func (ViewsTableModel) Rows

func (self ViewsTableModel) Rows() int

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL