Pages and Templates: Difference between revisions

From IHRIS Wiki
Line 158: Line 158:
Any scripts tags found in the body of the HTML  are moved to the header.
Any scripts tags found in the body of the HTML  are moved to the header.


=Tasks and Roles=
=Tareas y Roles=
[[Tasks and Roles|Tasks and roles]] are used to limit page access and well as the data displayed in the DOM.
Las [[Tasks and Roles|Tareas y Roles]] se utilizan para limitar el acceso a las páginas y los datos mostrados en el DOM.
[[Category:Technical Overview]][[Category:Pages]][[Category:Templates]][[Category:Review2013]][[Category:Needs Intro]]
[[Category:Technical Overview]][[Category:Pages]][[Category:Templates]][[Category:Review2013]][[Category:Needs Intro]]

Revision as of 22:06, 28 September 2013

Este tutorial describe el rol de las Páginas y las Plantillas en iHRIS.

Una página es la pieza básica que maneja cada solicitud URL. Es la unidad funcional básica del sistema en una petición de URL que se procesa y se muestra. Si desea añadir una nueva funcionalidad a iHRIS, muy probablemente tendrá que añadir una nueva página. Una página de ejemplo sería "Editar/añadir un documento escaneado."

Una plantilla se utiliza para acceder a los elementos HTML de una página. Se basa en el PHP Document Object Model.


Páginas

Las páginas pueden establecerse para que vivan directamente bajo la base URL de la página, o bajo un módulo y todas las solicitudes se delegan en la clase de página apropiada por el wrangler.

La lógica de una página se maneja por la clase de una página que tiene como sub-clase I2CE_Page por medio del método action() .

Las variables GET y POST variables son (por defecto) pre-procesadas por la clase de la página. Todas las páginas por defecto utilizan un templating que actúa como envoltura para el Document Object Model (DOM). También hay un sistema basado en permisos de task and role incluido.


También hay, por abuso de lenguaje, páginas para el PHP CLI. En este artículo sólo vamos a describir las páginas que URL Pide.

Clases de Páginas

Todas las solicitudes son finalmente delegadas por el wrangler a una subclase de I2CE_Page. Esta clase se encarga de toda la lógica de negocio de la página. Debe determinar la acción apropiada a desarrollar en función de si se trata de una solicitud de POST o GET. Varias páginas se pueden manejar por una clase de página. En la construcción, la página pasa una serie de arreglos de argumentos que se definen por page style y request remainder. Uno puede opcionalmente sobreescribir lo que se envía como el arreglo de las variables POST y GET.

Lógica de la Página

He aquí un resumen de la lógica de la página subyacente por defecto:

  • Las variables POST y GOT son (por lo general) pre-processed.
  • El conjunto de argumentos son producidos por el wrangler ya que procesa el estilo de la página.
  • Los archivos de plantilla raíz o principales, se hay alguno cargado. Esto se especifica como el argumento de 'templates'.
  • Los argumentos incluidos en esta página opcionalmente son restricciones de tareas y roles para la página:
    • Los roles que tienen permiso para ver la página se guardan bajo el 'access' clave
    • Las tareas que un user/role debe tener para ver la página se guardan en las 'tasks' clave
  • Una vez que el usuario ha pasado las restricciones de acceso de la página, lo siguiente ocurre:
    • El 'pre_page_action' hook se llama
    • Cualquier archivo html por defecto se carga para una página en los template que fueron creados para la página
      El archive html por defecto se guarda bajo el argumento 'defaultHTMLFile'
    • Se llama el método action()
    • Si el método de action() no regreso falso entonces se llama el 'post_page_action' hook
    • Si el método action() regresa falso entonces se genera un mensaje de error de usuario.
    • Si la página solicita una redirección, se realiza y la ejecución se detiene.
    • Si la página no solicito una redirección, entonces:
      • Cualquier declaración echo, print_r, etc. se adjuntan al final del DOM de la plantilla. Estos echo's, etc. solamente deben estar presente para propósitos de debugging y no en el código de producción.
      • A menos que la página solicito suprimir el resultado, la plantilla muestra su resultado(HTML) .
        Este es la única declaración echo que debe utilizarse en un sitio de producción para mostrar html.

El Método de action()

Una sub-clase de I2CE_Page generalmente debe implementar toda su lógica al sobreescribir el método action() .

Conversión de Variables

Las variables POST y GET, a menos que se les solicite específicamente no hacerlo, son pre-procesadas. Además de las variables POST y GET , las variables de SOLICITUD son creadas, que son (generalmente) cualquier variable que existe como POST o GET. Hay algunas cosas que ocurren (generalmente):

  • Si la variable GET 'req_query' existe, se adjunta el valor y se guarda como variables de SOLICITUD
  • Cualquier nombre de variables con ':' se procesan para definer arreglos de multi-dimensión. Por ejemplo:
$_GET = array(
  'some:thing'] => '5'
  'some:otherthing' => '6'
 )

se convierte en:

$_GET = array(
   'some'=>array(
       'thing'=>'5'
       'otherthing'=>'6'
   )
)
  • Si una variable se llama 'i2ce_json' es json_decode() y se fusiona de nuevo con las variables.

Wrangler

El wranger es el componente principal del software que delega las Solicitudes de URL primero a u par de un page name y módulo y luego a la clase de página apropiada. Supongamos para esta sección que nuestro sitio vive en el siguiente URL de base:

http://my.site.org/manage

Convertir un URL en Página

Las páginas pueden vivir directamente en el URL de base o bajo un módulo. El wrangler procesa el URL con el método I2CE_Wrangler->processPath() y regresa un page name, el page name del modulo se registra y un request remainder. El modulo bajo el que se registra un page name no es a menudo no el que proporciona la page class. Definamos la lógica para el ejemplo:

http://my.site.org/manage/some/thing/is/here
  • Si no hay nada después del URL de base, entonces el modulo es 'I2CE' y el page name es 'home'.
    No hay request remainder.
    Este no es el caso en el ejemplo de arriba.
  • Si 'some' se registra como page name dado por 'I2CE', entonces el modulo es 'I2CE' y el page name es 'some'.
    El request remainder es entonces thing/is/here.
    some se considera un page name registrado bajo 'I2CE' si el magic data path /I2CE/page/some existe.
  • De lo contrario el modulo es 'some' y las siguientes reglas aplican:
    • Si no hay nada después de 'some', entonces el moóulo es 'some' y el page name es 'home'
      No hay request remainder
      Este no es el caso en el ejemplo anterior.
    • Si 'thing' esta registrado como un page name para 'some' entonces, el modulo es 'some' y el page name es 'some.'.
      El request remainder es entonces is/here

Una vez que la ruta se ha procesado, verificamos que la pagina que regreró existe para el módulo dado. Si no, tratamos de manejar la solicitud buscando un default page name para el modulo. El default page name, si est adefinido, existe en la ruta de lso datos magic /modules/$module/default_page.

El modulo registrado, el page name, y el request remainder de llamado a todos puede verse a través de I2CE_Pages's API.

Estilos de Página

Una vez que tenemos un módulo válido y el nombre de la página asociada a un URL, comenzamos a procesar los estilos de la página. Un estilo de la página puede estar formado por tres componentes:

  • Otro estilo de página de la que esta hereda las propiedades
  • Una clase de página para asociarse a una página
  • Un arreglo anidado de argumentos para pasar al constructor de la clase de la página. Estos se combinan en los argumentos heredados por I2CE_Util::merge_recursive()

Plantillas

A cada instancia de página se le asigna una plantilla que es una instancia de I2CE_TemplateMeister, y por lo general una instancia de la sub-clase I2CE_Template.


La plantilla es esencialmente una clase contenedora para un objeto DOMDocument con algunos métodos de conveniencia útiles incluidos. Si bien la funcionalidad adicional proporcionada por el I2CE_TemplateMeister y I2CE_Template es inicialmente muy limitada, se aumenta en gran medida mediante el uso de fuzzy methods.

La página mostrará el DOM contenido en la plantilla como html una vez que la página ha terminado de procesar.


Template Data

La forma más significativa en que el caso del I2CE_Template se argumenta es proporcionar "Template Data." El modulo template-data ofrece la posibilidad de asignar datos arbitrarios a cualquier nodo en el DOM. Los datos existen en categorías, como 'FORM' u 'OPTION' y se aplica a todos los sub-nodos secundarios del nodo dado. A cada dato se le asigna un nombre.

Si el nodo es determinado especificando una id (en lugar de dar una instancia explícita de DOMNode) los datos se mantendrán en caché hasta que un nodo con la id dada se añada a la plantilla.

Al buscar algún dato asignado a un nodo concreto, empezamos por el nodo dado y caminamos hasta el DOM hasta encontrar el dato con nombre.

Para cada categoría de los datos de la plantilla, se puede asignar un poco de datos por defecto, lo que aplica para todo el DOM.

Hay varios módulos que hacen uso explícito de la estructura de datos de plantilla.

Advertencia: El mecanismo de los datos de plantilla supone que sólo hay una plantilla en uso por solicitud. Tenga mucho cuidado si utiliza varias plantillas en una página y cada una hace uso de los datos de la plantilla.

Display Data

Display data son datos de plantilla en la categoría 'DISPLAY' que pueden establecerse con los métodos inmediatps setDisplayData() y setDisplayDataImmediate() y proporcionar una forma conveniente de manipular los archivos de plantillas cargados. La plantilla buscará cualquier DOMElements con el atributo de nombre estabkecido y los procesará de acuerdo a su nombre de la etiqueta y los datos de la plantilla, si los hay, almacenados en el atributo de nombre. Aquí hay una lista de las etiquetas de uso general que se procesan y sus reglas:

  • div, pre, span, textarea: el valor de los datos de plantilla se anexa a la siguiente contenido del elemento
  • input: If the template data is an array, is is considered to be an array or attribute=>value pairs which are set on the element.
    If it is scalar valued, is is processed according to the value of the attribute type as follows::::
    • input: the attribute value is set to the value of the template data
    • checkbox: if it evaluates to true, then the attribute 'checked' is set. otherwise it is removed
  • select: If the value of the template data is an array, <option> tags are added with value attribute set to be the array key and the text content set to the corresponding array value
  • a: if the template data is of scalar type then:
    • if the href value is not set, it is set to be the value of the template data.
    • if the href is set the value template date is appended with either a ? or a & as appropriate to the href attribute
  • img: If the template data is an array, it is used as a set of attribute=>value pairs. If it is scalar, then the src attribute is set
  • form: If the template data is an array, it is used as a set of attribute=>value pairs. If it is scalar, then the action attribute is set
  • meta: If the template data is a scalar the content attribute is set
  • If the element has the attribute ifset with (case insensitive) value 'true' or 't' or '1' and the template data is not set, then it is removed.
  • If the element has the attribute ifset with (case insensitive) value other than 'true' or 't' or '1' and the template data is set, then it not removed.

Options

Closely related to the Display Data module is the Options module which saves template data in the category 'OPTIONS.' It process tags of the form:

<select id='some_id'/>

and if it finds an OPTION template data named 'some_id' it will append a <select> tag for each of these bits of data.

Form Data

A form can be set on any node and can be referenced as

<span type='form' name='form:field'/>

where you would substitute 'form' and 'field' as appropriate. If the 'form' is not specified it uses the default form, if any, set for the page.

Module Attribute

Any DOM Elements with the attribute type set to be 'module' and 'name' attribute are processed according to certain rules. The value of the name attribute is the name of a module. The following attributes are recognized:

  • ifenabled: can be t, true, !t or !true. If true and the module is not enabled, or false and the module is enabled the the node is removed.
  • if: Tries to call the module's function with the value of the attribute 'if.' If the module returns (something which casts to) false the node is removed. Prepending the value with a ! causes the opposite behavior.
  • call: The value is used as the value of a method to call in the module's class.

Suppose we have

someMethod($node,$template,$args)

where $node is the <span> node, $template is the template object and the argument is the array of arguments $args = ($arg1,..,$argN) where [argM] is turned into $argM according to the following rules:

  • if [argM] starts with a $ then it refers to template data and the following rules apply:
    • The string has the form $abcd. The value of $argM becomes the template display data with name 'abcd.'
    • The string has the form ${WXYZ}abcd. The value of $argM becomes the template data with category XYZ and with name 'abcd.'
  • <NODE> becomes the instance of DOMNode (if any) that the permission string was called on
  • <TEMPLATE> becomes the instance of I2CE_Template (if any) that the permission parser was called on
  • <USER> becomes the instance of I2CE_User that is this session
  • if [argM] starts with a single quote ' then it is a string until the next non-escaped ' is found
  • if [argM] starts with a double quote " then is is a string until the next non-escaped " is found.
    In addition the following substitution rules apply:
    • any substring starting with $ and consisting of alpha-numeric characters, - or _ is interpreted as template display data to be substituted
      For example "my name is $name" becomes "my name is Joe" if the template data named 'name' and with type DISPLAY is "Joe"
    • any substring starting with {$ is read until an enclosing } is found. The string between the ${ and } is the name of DISPLAY template data which is then substituted.
    • To prevent the above, { and $ may be escaped with a \
  • any string of of alpha-numeric character (and a few permitted punctuation marks) are interpreted as follows:
    • if is is of the form abcd(, then it is interpreted as another method to call on $module as:
      $module->abcd($subargs)
      where sub-args are processed (recursively) according to the same rules and bounded by the next enclosing )
    • otherwise if is is of the form wxyz->abcd(, then it is interpreted as another method to call on $sub_module as:
      $sub_module->abcd($subargs)
      where sub-args are processed (recursively) according to the same rules and bounded by the next enclosing ) and $sub_module is the module class instance associated with wxyz
  • otherwise it is interpreted as a string

Arguments are separated by spaces or commas

Tags

As "special cases" of moudle functions, following attributes are scanned for and processed:

  • printf attribute: Appends to the node the results of printf substitution of the string with the specified arguments. It also is locale aware and can make use of plural forms.
    printf="'this is something %s',$data'

Scripts

Any scripts tags found in the body of the HTML are moved to the header.

Tareas y Roles

Las Tareas y Roles se utilizan para limitar el acceso a las páginas y los datos mostrados en el DOM.