view

package
v0.0.0-...-9012c6e Latest Latest
Warning

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

Go to latest
Published: May 22, 2012 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

The View of MVC.

Index

Constants

View Source
const (
	TextAreaDefaultCols = 80
	TextAreaDefaultRows = 3
)
View Source
const LoremIpsum = "" /* 3101-byte string literal not displayed */
View Source
const PathFragmentPattern = "([a-zA-Z0-9_\\-\\.]+)"

Variables

Functions

func Close

func Close()

func DeleteViewID

func DeleteViewID(id string)

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 Init

func Init(siteName, cookieSecret string, baseDirs ...string) (err error)

Init updates Config with the site-name, cookie secret and base directories used for static and template file search. For every directory of baseDirs, Config.StaticDirs are appended to create search paths for static files and Config.TemplateDirs are appended to search for template files.

func JQuery

func JQuery(context *Context, writer io.Writer) (err error)

func JQueryUI

func JQueryUI(context *Context, writer io.Writer) (err error)

func NewViewID

func NewViewID(view View) (id string)

func RenderChildViewsHTML

func RenderChildViewsHTML(parent View, context *Context, writer *utils.XMLWriter) (err error)

func RenderTemplate

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

func Run

func Run(paths *ViewPath, address, baseURL string, recoverPanic bool)

func RunConfigFile

func RunConfigFile(paths *ViewPath, filename string)

Types

type AllAuthenticators

type AllAuthenticators []Authenticator

AllAuthenticators returns true if all of its authenticators return true.

func (AllAuthenticators) Authenticate

func (self AllAuthenticators) Authenticate(context *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(context *Context) (ok bool, err error)

type Authenticator

type Authenticator interface {
	// Authenticate returns the auth result in ok,
	// err is used for real errors not negative authentication
	Authenticate(context *Context) (ok bool, err error)
}

Authenticator authenticates the user of a request context.

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(context *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(context *Context) (ok bool, err error)

type Button

type Button struct {
	ViewBaseWithId
	Name     string
	Value    interface{}
	Submit   bool
	Class    string
	Disabled bool
	TabIndex int
}

Button represents a HTML input element of type button or submit.

func (*Button) Render

func (self *Button) Render(context *Context, writer *utils.XMLWriter) (err error)

type CSRFProtector

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

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(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (err error)

type Configuration

type Configuration struct {
	TemplateSystem     templatesystem.Implementation
	Page               PageConfiguration
	Form               FormConfiguration
	BaseDirs           []string
	StaticDirs         []string
	TemplateDirs       []string
	RedirectSubdomains []string // Exapmle: "www"
	BaseURL            string
	SiteName           string
	CookieSecret       string
	SessionTracker     SessionTracker
	SessionDataStore   SessionDataStore
	OnPreAuth          func(context *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
	LoginSignupPage    **Page
	// Middlewares               []Middleware
	Debug struct {
		Mode           bool
		PrintPaths     bool
		PrintRedirects bool
	}
}
var Config Configuration = Configuration{
	TemplateSystem: &templatesystem.Mustache{},
	Page: PageConfiguration{
		Template:            "html5boilerplate.html",
		DefaultCSS:          "/style.css",
		DefaultMetaViewport: "width=device-width",
	},
	Form: FormConfiguration{
		DefaultLayout:              new(VerticalFormLayout),
		DefaultFieldFactory:        new(StandardFormFieldFactory),
		DefaultCSRFProtector:       nil,
		DefaultErrorMessageClass:   "error",
		DefaultSuccessMessageClass: "success",
		DefaultRequiredMarker:      HTML("<span class='required'>*</span>"),
		NumFieldRepeatMessage:      6,
	},
	BaseDirs:         []string{"."},
	StaticDirs:       []string{"static"},
	TemplateDirs:     []string{"templates"},
	SessionTracker:   &CookieSessionTracker{},
	SessionDataStore: NewCookieSessionDataStore(),
}

Config holds the configuration of the view package.

type ContactFormModel

type ContactFormModel struct {
	Name    model.String `gostart:"label=Your name|maxlen=40"`
	Email   model.Email  `gostart:"label=Your email address|required|maxlen=40"`
	Subject model.String `gostart:"label=Subject|maxlen=40"`
	Message model.Text   `gostart:"label=Your message|required|cols=40|rows=10"`
}

ContactFormModel is a default form model for contact forms.

type Context

type Context struct {
	*web.Context

	// View that responds to the HTTP request
	RespondingView View

	// Arguments parsed from the URL path
	PathArgs []string

	/*
		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(context *Context) error {
				user.OfSession(context) // Sets context.User
				return nil
			}
	*/
	User interface{}

	// Custom request wide data that can be set by the application
	Data interface{}
	// contains filtered or unexported fields
}

Context holds all data specific to a HTTP request and will be passed to View.Render() methods.

func NewContext

func NewContext(webContext *web.Context, respondingView View, pathArgs []string) *Context

func (*Context) DecryptCookie

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

func (*Context) DeleteSessionData

func (self *Context) DeleteSessionData() (err error)

DeleteSessionData deletes all session data.

func (*Context) DeleteSessionID

func (self *Context) DeleteSessionID()

func (*Context) EncryptCookie

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

func (*Context) ParseRequestUserAgent

func (self *Context) ParseRequestUserAgent() (renderer string, version utils.VersionTuple, err error)

todo: all browsers

func (*Context) RequestPort

func (self *Context) RequestPort() uint16

func (*Context) RequestURL

func (self *Context) RequestURL() string

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

func (*Context) SessionData

func (self *Context) SessionData(out interface{}) (ok bool, err error)

SessionData returns all session data in out.

func (*Context) SessionID

func (self *Context) SessionID() (id string, ok bool)

SessionID returns the id of the session and if there is a session active.

func (*Context) SetSessionData

func (self *Context) SetSessionData(data interface{}) (err error)

SetSessionData sets all session data.

func (*Context) SetSessionID

func (self *Context) SetSessionID(id string)

type CookieSessionDataStore

type CookieSessionDataStore struct {
	// contains filtered or unexported fields
}

func (*CookieSessionDataStore) Delete

func (self *CookieSessionDataStore) Delete(context *Context) (err error)

func (*CookieSessionDataStore) Get

func (self *CookieSessionDataStore) Get(context *Context, data interface{}) (ok bool, err error)

func (*CookieSessionDataStore) Set

func (self *CookieSessionDataStore) Set(context *Context, data interface{}) (err error)

type CookieSessionTracker

type CookieSessionTracker struct {
}

http://en.wikipedia.org/wiki/HTTP_cookie

func (*CookieSessionTracker) DeleteID

func (self *CookieSessionTracker) DeleteID(context *Context)

func (*CookieSessionTracker) ID

func (self *CookieSessionTracker) ID(context *Context) (id string, ok bool)

func (*CookieSessionTracker) SetID

func (self *CookieSessionTracker) SetID(context *Context, id string)

type Div

type Div struct {
	ViewBaseWithId
	Class   string
	Content View
}

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(context *Context, writer *utils.XMLWriter) (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 (*DummyImage) Render

func (self *DummyImage) Render(context *Context, writer *utils.XMLWriter) (err error)

type DynamicView

type DynamicView func(context *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(context *Context) (view View, err error) {
		return HTML("return dynamic created views here"), nil
	},
)

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(context *Context, writer *utils.XMLWriter) error

type EscapeStringsListModel

type EscapeStringsListModel []string

func (EscapeStringsListModel) ItemView

func (self EscapeStringsListModel) ItemView(index int, context *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, context *Context) (view View, err error)

func (EscapeStringsTableModel) Columns

func (self EscapeStringsTableModel) Columns() int

func (EscapeStringsTableModel) Rows

func (self EscapeStringsTableModel) Rows() int

type Forbidden

type Forbidden string

func (Forbidden) Error

func (self Forbidden) Error() string

type Form

type Form struct {
	ViewBaseWithId
	Class         string
	Action        string // Default is "." plus any URL params
	Method        string
	FormID        string
	CSRFProtector CSRFProtector
	Layout        FormLayout       // Config.DefaultFormLayout will be used if nil
	FieldFactory  FormFieldFactory // Config.DefaultFormFieldFactory will be used if nil
	// Static content rendered before the dynamic form fields
	// that are generated via GetModel()
	StaticContent View
	GetModel      GetFormModelFunc
	// If redirect result is non nil, it will be used instead of Form.Redirect
	OnSubmit            func(form *Form, formModel interface{}, context *Context) (redirect URL, err error)
	ModelMaxDepth       int      // if zero, no depth limit
	ExcludeFields       []string // Use point notation for nested fields
	DisableFields       []string // Use point notation for nested fields
	RequireFields       []string // Also available as static struct field tag. Use point notation for nested fields
	ErrorMessageClass   string   // If empty, Config.Form.DefaultErrorMessageClass will be used
	SuccessMessageClass string   // If empty, Config.Form.DefaultSuccessMessageClass will be used
	RequiredMarker      View     // If nil, Config.Form.DefaultRequiredMarker will be used
	SuccessMessage      string
	SubmitButtonText    string
	SubmitButtonClass   string
	Redirect            URL // 302 redirect after successful Save()
	ShowRefIDs          bool
}

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

func (self *Form) GetFieldFactory() FormFieldFactory

GetFieldFactory returns self.FieldFactory if not nil, else Config.Form.DefaultFieldFactory will be returned.

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

func (self *Form) GetSuccessMessageClass() string

func (*Form) IsFieldDisabled

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

func (*Form) IsFieldRequired

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

func (*Form) IterateChildren

func (self *Form) IterateChildren(callback IterateChildrenCallback)

func (*Form) Render

func (self *Form) Render(context *Context, writer *utils.XMLWriter) (err error)

type FormConfiguration

type FormConfiguration struct {
	DefaultLayout              FormLayout
	DefaultFieldFactory        FormFieldFactory
	DefaultCSRFProtector       CSRFProtector
	DefaultErrorMessageClass   string
	DefaultSuccessMessageClass string
	DefaultSubmitButtonClass   string
	DefaultRequiredMarker      View
	NumFieldRepeatMessage      int
}

type FormFieldFactory

type FormFieldFactory interface {
	NewInput(form *Form, data interface{}, metaData *model.MetaData) View
	NewLabel(form *Form, forView View, data interface{}, metaData *model.MetaData) View
	NewFieldErrorMessage(form *Form, message string, metaData *model.MetaData) View
	NewFormErrorMessage(form *Form, message string) View
	NewSuccessMessage(form *Form, message string) View
	NewSubmitButton(form *Form, text string) View
	NewAddSliceItemButton(form *Form) View
	NewRemoveSliceItemButton(form *Form) View
}

type FormLayout

type FormLayout interface {
	NewField_old(form *Form, modelValue model.Value, metaData *model.MetaData, errors []*model.ValidationError) View

	BeforeFormContent(form *Form) View
	AfterFormContent(form *Form) View

	BeforeStruct(form *Form, data interface{}, metaData *model.MetaData) View
	StructField(form *Form, data interface{}, metaData *model.MetaData) View
	AfterStruct(form *Form, data interface{}, metaData *model.MetaData) View

	BeforeArray(form *Form, data interface{}, metaData *model.MetaData) View
	ArrayField(form *Form, data interface{}, metaData *model.MetaData) View
	AfterArray(form *Form, data interface{}, metaData *model.MetaData) View

	BeforeSlice(form *Form, data interface{}, metaData *model.MetaData) View
	SliceField(form *Form, data interface{}, metaData *model.MetaData) View
	AfterSlice(form *Form, data interface{}, metaData *model.MetaData) View
}

FormLayout is responsible for creating and structuring all dynamic content of the form including the submit button. It uses From.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(context *Context, writer *utils.XMLWriter) (err error)

type GetFormModelFunc

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

func FormModel

func FormModel(model interface{}) GetFormModelFunc

type GetModelIteratorFunc

type GetModelIteratorFunc func(context *Context) model.Iterator

func ModelIterator

func ModelIterator(iter model.Iterator) GetModelIteratorFunc

type GetModelViewFunc

type GetModelViewFunc func(model interface{}, context *Context) (view View, err error)

type GetTemplateContextFunc

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

func TemplateContext

func TemplateContext(context interface{}) GetTemplateContextFunc

type HTML

type HTML string

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 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 (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(context *Context, writer *utils.XMLWriter) (err error)

type HTMLStringsListModel

type HTMLStringsListModel []string

func (HTMLStringsListModel) ItemView

func (self HTMLStringsListModel) ItemView(index int, context *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, context *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(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (err error)

type Image

type Image struct {
	ViewBaseWithId
	Class       string
	URL         string
	Width       int
	Height      int
	Description string
}

func (*Image) Render

func (self *Image) Render(context *Context, writer *utils.XMLWriter) (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, context *Context, writer *utils.XMLWriter) (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 Label

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

func (*Label) Render

func (self *Label) Render(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (err error)

type LinkModel

type LinkModel interface {
	URL
	LinkContent(context *Context) View
	LinkTitle(context *Context) string
	LinkRel(context *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(context *Context, writer *utils.XMLWriter) (err error)

type ListModel

type ListModel interface {
	NumItems() int
	ItemView(index int, context *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(context *Context, writer *utils.XMLWriter) (err error)

type Middleware

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

type ModelView

type ModelView struct {
	ViewBase
	GetModelIterator GetModelIteratorFunc
	GetModelView     GetModelViewFunc // nil Views will be ignored
}

func (*ModelView) Render

func (self *ModelView) Render(context *Context, writer *utils.XMLWriter) (err error)

type MultiViewsListModel

type MultiViewsListModel []Views

func (MultiViewsListModel) ItemView

func (self MultiViewsListModel) ItemView(index int, context *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(context *Context, writer *utils.XMLWriter) (err error)

type Page

type Page struct {
	Template

	// Called before any other function when rendering the page
	OnPreRender func(page *Page, context *Context) (err error)

	// Writes the head title tag (HTML escaped)
	WriteTitle PageWriteFunc

	// Writes the head meta description tag (HTML escaped)
	WriteMetaDescription PageWriteFunc

	// Content of the head meta viewport tag,
	// Config.Page.DefaultMetaViewport will be used if ""
	MetaViewport string

	// Write additional HTML head content
	WriteHead PageWriteFunc

	// Write head content before the stylesheet link
	WritePreCSS PageWriteFunc

	// stylesheet link URL
	CSS URL

	// Write head content after the stylesheet link
	WritePostCSS PageWriteFunc

	// Write scripts as last element of the HTML head
	WriteHeadScripts PageWriteFunc

	// HTML body content. Will be wrapped by a div with class="container"
	Content View

	// Write scripts after body content
	WriteScripts PageWriteFunc

	// 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 PageWriteFunc 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 PageWriteFunc below.

Example:

&Page{WriteTitle: func(context *Context, 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 PageWriteFunc 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, context *Context) (err error) {
		context.Data = &MyPerPageData{SomeText: "Hello World!"}
	},
	Content: DynamicView(
		func(context *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(context *Context) View

Implements the LinkModel interface

func (*Page) LinkRel

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

Implements the LinkModel interface

func (*Page) LinkTitle

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

Implements the LinkModel interface

func (*Page) Render

func (self *Page) Render(context *Context, writer *utils.XMLWriter) (err error)

func (*Page) SetPath

func (self *Page) SetPath(path string)

func (*Page) URL

func (self *Page) URL(context *Context, args ...string) string

Implements the URL and LinkModel interface

type PageConfiguration

type PageConfiguration struct {
	Template                string
	DefaultWriteHead        PageWriteFunc // will be called after WriteTitle
	DefaultCSS              string
	DefaultMetaViewport     string
	DefaultWriteHeadScripts PageWriteFunc // write scripts as last element of the HTML head
	DefaultWriteScripts     PageWriteFunc // will be called if Page.WriteScripts is nil
	PostWriteScripts        PageWriteFunc // 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   // If is nil, then self.LinkTitle() will be used
	Title   string // If is "", then self.Page.LinkTitle(context) will be used
	Rel     string
}
func NewPageLink(page **Page, title string) *PageLink

func (*PageLink) LinkContent

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

func (*PageLink) LinkRel

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

func (*PageLink) LinkTitle

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

func (*PageLink) URL

func (self *PageLink) URL(context *Context, args ...string) string

type PageWriteFunc

type PageWriteFunc func(context *Context, writer io.Writer) (err error)

PageWriteFunc is used by Page to write dynamic or static content to the page.

func GoogleAnalytics

func GoogleAnalytics(trackingID string) PageWriteFunc

func GoogleMaps

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

todo: replace http with https if necessary

func IndirectPageWriter

func IndirectPageWriter(pageWritePtr *PageWriteFunc) PageWriteFunc

IndirectPageWriter takes the pointer to a PageWriteFunc variable and dereferences it when the returned PageWriteFunc is called. Used to break dependency cycles of variable initializations by using a pointer to a variable instead of its value.

func JQueryUIAutocomplete

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

func JQueryUIAutocompleteFromURL

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

func PageMetaDescription

func PageMetaDescription(description string) PageWriteFunc

PageMetaDescription writes a static meta description.

func PageTitle

func PageTitle(title string) PageWriteFunc

PageTitle writes a static page title.

func PageWrite

func PageWrite(text string) PageWriteFunc

PageWrite writes static text.

func PageWriters

func PageWriters(funcs ...PageWriteFunc) PageWriteFunc

PageWriters combines multiple PageWriteFunc into a single PageWriteFunc by calling them one after another.

func PageWritersFilterPort

func PageWritersFilterPort(port uint16, funcs ...PageWriteFunc) PageWriteFunc

PageWritersFilterPort calls funcs only if the request is made to a specific port

func RSS

func RSS(title string, url URL) PageWriteFunc

RSS a application/rss+xml link tag with the given title and url.

func Script

func Script(script string) PageWriteFunc

Script writes a HTML script tag with the passed script as content.

func ScriptURL

func ScriptURL(url string) PageWriteFunc

ScriptURL writes a HTML script tag with that references url.

func Stylesheet

func Stylesheet(css string) PageWriteFunc

Stylesheet writes a HTML style tag with the passed css as content.

func StylesheetURL

func StylesheetURL(url string) PageWriteFunc

StylesheetURL writes a HTML style tag with that references url.

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(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (err error)

type RenderView

type RenderView func(context *Context, writer *utils.XMLWriter) error

RenderView implements all View methods for a View.Render compatible function.

Example:

renderView := RenderView(
	func(context *Context, writer *utils.XMLWriter) error {
		writer.Write([]byte("<html><body>Any Content</body></html>"))
		return nil
	},
)

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(context *Context, writer *utils.XMLWriter) error

type Request

type Request struct {
	// contains filtered or unexported fields
}

not used atm.

type Response

type Response struct {
	utils.XMLBuffer
	// contains filtered or unexported fields
}

not used atm.

func (*Response) NotFound404

func (self *Response) NotFound404(url string)

func (*Response) NotModified304

func (self *Response) NotModified304(url string)

func (*Response) RedirectPermanently301

func (self *Response) RedirectPermanently301(url string)

func (*Response) RedirectTemporary302

func (self *Response) RedirectTemporary302(url string)

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(context *Context, writer *utils.XMLWriter) (err error)

type SelectModel

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

type Session

type Session struct {
}

type SessionDataStore

type SessionDataStore interface {
	Get(context *Context, data interface{}) (ok bool, err error)
	Set(context *Context, data interface{}) (err error)
	Delete(context *Context) (err error)
}

func NewCookieSessionDataStore

func NewCookieSessionDataStore() SessionDataStore

type SessionTracker

type SessionTracker interface {
	ID(context *Context) (id string, ok bool)
	SetID(context *Context, id string)
	DeleteID(context *Context)
}

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(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (err error)

type StandardFormFieldFactory

type StandardFormFieldFactory struct {
}

func (*StandardFormFieldFactory) NewAddSliceItemButton

func (self *StandardFormFieldFactory) NewAddSliceItemButton(form *Form) View

func (*StandardFormFieldFactory) NewFieldErrorMessage

func (self *StandardFormFieldFactory) NewFieldErrorMessage(form *Form, message string, metaData *model.MetaData) View

func (*StandardFormFieldFactory) NewFormErrorMessage

func (self *StandardFormFieldFactory) NewFormErrorMessage(form *Form, message string) View

func (*StandardFormFieldFactory) NewInput

func (self *StandardFormFieldFactory) NewInput(form *Form, data interface{}, metaData *model.MetaData) View

func (*StandardFormFieldFactory) NewLabel

func (self *StandardFormFieldFactory) NewLabel(form *Form, forView View, data interface{}, metaData *model.MetaData) View

func (*StandardFormFieldFactory) NewRemoveSliceItemButton

func (self *StandardFormFieldFactory) NewRemoveSliceItemButton(form *Form) View

func (*StandardFormFieldFactory) NewSubmitButton

func (self *StandardFormFieldFactory) NewSubmitButton(form *Form, text string) View

func (*StandardFormFieldFactory) NewSuccessMessage

func (self *StandardFormFieldFactory) NewSuccessMessage(form *Form, message string) View

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(context *Context, writer *utils.XMLWriter) (err error)
type StringLink struct {
	Url     string
	Content View   // If is nil, then self.LinkTitle() will be used
	Title   string // If is "", then self.URL will be used
	Rel     string
}

func (*StringLink) LinkContent

func (self *StringLink) LinkContent(context *Context) View

func (*StringLink) LinkRel

func (self *StringLink) LinkRel(context *Context) string

func (*StringLink) LinkTitle

func (self *StringLink) LinkTitle(context *Context) string

func (*StringLink) URL

func (self *StringLink) URL(context *Context, args ...string) string

type StringURL

type StringURL string

StringURL implements the URL interface for a string.

func (StringURL) URL

func (self StringURL) URL(context *Context, args ...string) 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, context *Context, writer *utils.XMLWriter) (err error)

func (*StringsSelectModel) Selected

func (self *StringsSelectModel) Selected(index int) bool

func (*StringsSelectModel) Value

func (self *StringsSelectModel) Value(index int) string

type Table

type Table struct {
	ViewBaseWithId
	Model     TableModel
	Class     string
	Caption   string
	HeaderRow bool
}

func (*Table) Render

func (self *Table) Render(context *Context, writer *utils.XMLWriter) (err error)

type TableModel

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

type TableModelView

type TableModelView struct {
	ViewBase
	Class             string
	Caption           string
	GetModelIterator  GetModelIteratorFunc
	GetHeaderRowViews func(context *Context) (views Views, err error)
	GetRowViews       func(row int, rowModel interface{}, context *Context) (views Views, err error)
	// contains filtered or unexported fields
}

func (*TableModelView) IterateChildren

func (self *TableModelView) IterateChildren(callback IterateChildrenCallback)

func (*TableModelView) Render

func (self *TableModelView) Render(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (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(requestContext *Context, writer *utils.XMLWriter) (err error)

type TextArea

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

func (*TextArea) Render

func (self *TextArea) Render(context *Context, writer *utils.XMLWriter) (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
}

func (*TextField) Render

func (self *TextField) Render(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (err error)

type URL

type URL interface {
	// If args are passed, they will be used instead of context.PathArgs.
	URL(context *Context, args ...string) string
}

URL is an interface to return URL strings depending on the request context.

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 when they are initialized.

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
}

func (*URLLink) LinkContent

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

func (*URLLink) LinkRel

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

func (*URLLink) LinkTitle

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

func (*URLLink) URL

func (self *URLLink) URL(context *Context, args ...string) string

type VerticalFormLayout

type VerticalFormLayout struct {
}

VerticalFormLayout.

CSS needed for VerticalFormLayout:

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 (*VerticalFormLayout) AfterArray

func (self *VerticalFormLayout) AfterArray(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) AfterFormContent

func (self *VerticalFormLayout) AfterFormContent(form *Form) View

func (*VerticalFormLayout) AfterSlice

func (self *VerticalFormLayout) AfterSlice(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) AfterStruct

func (self *VerticalFormLayout) AfterStruct(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) ArrayField

func (self *VerticalFormLayout) ArrayField(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) BeforeArray

func (self *VerticalFormLayout) BeforeArray(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) BeforeFormContent

func (self *VerticalFormLayout) BeforeFormContent(form *Form) View

func (*VerticalFormLayout) BeforeSlice

func (self *VerticalFormLayout) BeforeSlice(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) BeforeStruct

func (self *VerticalFormLayout) BeforeStruct(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) NewField_old

func (self *VerticalFormLayout) NewField_old(form *Form, modelValue model.Value, metaData *model.MetaData, errors []*model.ValidationError) View

func (*VerticalFormLayout) SliceField

func (self *VerticalFormLayout) SliceField(form *Form, data interface{}, metaData *model.MetaData) View

func (*VerticalFormLayout) StructField

func (self *VerticalFormLayout) StructField(form *Form, data interface{}, metaData *model.MetaData) View

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(context *Context, writer *utils.XMLWriter) (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(context *Context, writer *utils.XMLWriter) (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 IMG

func IMG(url string, dimensions ...int) View

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

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

func PRE

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

func Q

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

func SECTION

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

func STRONG

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

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(context *Context, writer *utils.XMLWriter) (err error)

func (*ViewURLWrapper) SetPath

func (self *ViewURLWrapper) SetPath(path string)

func (*ViewURLWrapper) URL

func (self *ViewURLWrapper) URL(context *Context, args ...string) 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

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 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(context *Context, writer *utils.XMLWriter) (err error)

type ViewsListModel

type ViewsListModel []View

func (ViewsListModel) ItemView

func (self ViewsListModel) ItemView(index int, context *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, context *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