diff --git a/.gitignore b/.gitignore index 38cdbd7..0aba878 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,6 @@ composer.phar composer.lock .DS_Store -.idea \ No newline at end of file +.idea +/.vscode +.phpunit.result.cache diff --git a/.travis.yml b/.travis.yml index 2c76ad7..995087a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,8 +2,7 @@ language: php php: - - 5.6 - - 7.0 + - 7.3 sudo: false @@ -11,7 +10,7 @@ install: composer install script: - - vendor/bin/phpspec + - vendor/bin/phpunit matrix: - fast_finish: true \ No newline at end of file + fast_finish: true diff --git a/LEEME.md b/LEEME.md index 9f4697a..96cf5cb 100644 --- a/LEEME.md +++ b/LEEME.md @@ -202,7 +202,7 @@ Este paquete extiende la funcionalidad del HTML Builder de the Laravel Collectiv Hay un solo método adicional _por ahora_, pero ¡es muy útil! -####Generar clases de CSS: +#### Generar clases de CSS: ```blade {!! Html::classes(['home' => true, 'main', 'dont-use-this' => false]) !!} @@ -220,7 +220,9 @@ Además de utilizar los métodos facade `Alert::message` y `Menu::make`, puedes alert('this is the message', 'type-of-message') ``` -`menu($items, $clases)` +```php +menu($items, $clases) +``` ## Access handler diff --git a/README.md b/README.md index 23ae56c..4494098 100644 --- a/README.md +++ b/README.md @@ -19,18 +19,6 @@ This is an extension of the Laravel Collective [HTML package](https://github.com Install by running `composer require "styde/html=~1.3"` or adding `"styde/html": "~1.3"` to your `composer.json` file and then running `composer update`. -**Laravel 5.3 users**: - -Install by running `composer require "styde/html=~1.2"` or adding `"styde/html": "~1.2"` to your `composer.json` file and then running `composer update`. - -**Laravel 5.2 users**: - -Install by running `composer require "styde/html=~1.1"` or adding `"styde/html": "~1.1"` to your `composer.json` file and then running `composer update`. - -**Laravel 5.1 users**: - -Install by running `composer require "styde/html=~1.0"` or adding `"styde/html": "~1.0"` to your `composer.json` file and then running `composer update`. - 2. Next, add the new provider to the `providers` array in `config/app.php` ```php @@ -41,18 +29,12 @@ Install by running `composer require "styde/html=~1.0"` or adding `"styde/html": ], ``` -3. Also, you need to register in the `app/Http/Kernel.php` file the `\Styde\Html\Alert\Middleware::class` middleware **BEFORE** the `EncryptCookies` middleware. For Laravel 5.4, it's in the `$middlewareGroups` array and for previous versions (Laravel 5.3, 5.2, 5.1) it's in the `$middleware` array: +3. Also, you need to register in the `app/Http/Kernel.php` file the `\Styde\Html\Alert\Middleware::class` middleware **AFTER** the `StartSession` middleware in the `$middlewareGroups` array: ```php // For Laravel 5.4 protected $middlewareGroups = [ - \Styde\Html\Alert\Middleware::class, - //... -]; - -// For Laravel 5.3, 5.2, 5.1 -protected $middleware = [ - //... + // For Laravel 5.8 and later this needs to be after the StartSession middleware \Styde\Html\Alert\Middleware::class, //... ]; @@ -224,7 +206,9 @@ In addition of using the facade methods `Alert::message` and `Menu::make`, you c alert('this is the message', 'type-of-message') ``` -`menu($items, $classes)` +```php +menu($items, $classes) +``` ## Access handler diff --git a/composer.json b/composer.json index 308de96..86a6330 100644 --- a/composer.json +++ b/composer.json @@ -9,12 +9,12 @@ } ], "require": { - "php": ">=5.5.9", - "laravelcollective/html": "5.4.*", - "laravel/framework": "5.4.*" + "php": "^8.2", + "laravel/framework": "^11.0" }, "require-dev": { - "phpspec/phpspec": "~2.1" + "phpunit/phpunit": "^11.0", + "orchestra/testbench": "^9.0" }, "autoload": { "psr-4": { @@ -24,5 +24,25 @@ "src/helpers.php" ] }, - "minimum-stability": "stable" + "autoload-dev": { + "psr-4": { + "Styde\\Html\\Tests\\": "tests/" + } + }, + "extra": { + "laravel": { + "providers": [ + "Styde\\Html\\HtmlServiceProvider" + ], + "aliases": { + "Field": "Styde\\Html\\Facades\\Field", + "Alert": "Styde\\Html\\Facades\\Alert", + "Menu": "Styde\\Html\\Facades\\Menu", + "Form": "Styde\\Html\\Facades\\Form", + "Html": "Styde\\Html\\Facades\\Html" + } + } + }, + "minimum-stability": "dev", + "prefer-stable": true } diff --git a/config.php b/config.php index cec83f5..dab8f0e 100644 --- a/config.php +++ b/config.php @@ -6,20 +6,13 @@ * Set the HTML theme for the components * like alerts, form fields, menus, etc. */ - 'theme' => 'bootstrap', + 'theme' => 'bootstrap4', /* * Set the folder to store the custom templates */ 'custom' => 'themes', - /* - * Set to false to deactivate the AccessHandler component - * Doing so the component will run slightly faster but - * the logged and roles checkers won't be available - */ - 'control_access' => true, - /* * Set to false to deactivate the Translator for the alert and menu * components, doing so they will run slightly faster but won't @@ -37,23 +30,14 @@ */ 'novalidate' => false, - /* - * Specify abbreviations for the form field attributes - */ - 'abbreviations' => [ - 'ph' => 'placeholder', - 'max' => 'maxlength', - 'tpl' => 'template' - ], - /* * Set the configuration for each theme */ 'themes' => [ /** - * Default configuration for the Twitter Bootstrap framework + * Default configuration for Bootstrap v4 */ - 'bootstrap' => [ + 'bootstrap4' => [ /* * Set a specific HTML template for a field type if the * type is not set, the default template will be used @@ -63,17 +47,34 @@ 'checkbox' => 'checkbox', 'checkboxes' => 'collections', 'radios' => 'collections' + ] + ], + /** + * Configuration for Bulma CSS v1.7.2 + */ + 'bulma' => [ + /* + * Set a specific HTML template for a field type if the + * type is not set, the default template will be used + */ + 'field_templates' => [ + // type => template + 'checkbox' => 'checkbox', + 'checkboxes' => 'collections', + 'radios' => 'collections', + 'select'=>'selects', + ], /* * Set the default classes for each field type */ 'field_classes' => [ // type => class or classes - 'default' => 'form-control', - 'checkbox' => '', - 'error' => 'input-with-feedback' + 'textarea' => 'textarea', + 'default' => 'input', + 'checkbox' => 'checkbox', + 'error' => 'is-danger' ], ] ] - ]; diff --git a/docs/access-handler.md b/docs/access-handler.md index b582585..48673eb 100644 --- a/docs/access-handler.md +++ b/docs/access-handler.md @@ -11,40 +11,45 @@ Just pass one of the following options as a field attribute or menu item value: 1. *callback*: should return true if you want to grant access, false otherwise. 2. *logged*: true: requires authenticated user, false: requires guest user. 3. *roles*: true if the user has any of the required roles. -4. *allows*: uses the Gate::allows method +4. *allows*: uses the Gate::allows method 5. *check*: uses the Gate::check method (alias of allow) 6. *denies*: uses the Gate::denies method 7. If no option is passed, this will return true (the item will be rendered) *WARNING*: note this package will only prevents the elements from appearing in the front end, you still need to protect the backend access using middleware, etc. -##Usage +## Usage #### Form fields -`{!! Field::select('user_id', null, ['role' => 'admin'])` +```blade +{!! Field::select('user_id', null, ['role' => 'admin']) !!} +``` #### Menu items -``` +```php + [ 'account' => [ - 'logged' => true + 'logged' => true, ], 'login' => [ - 'logged' => false + 'logged' => false, ], 'settings' => [ - 'roles' => 'admin' - ] - ] + 'roles' => 'admin', + ], + ], ]; ``` - -`{!! Menu::make('menu.items') !}}` + +```blade +{!! Menu::make('menu.items') !}} +``` ## Gate authorization @@ -52,32 +57,40 @@ The allows, check and denies options accept a string or an array as a value. If it is an string, it will be the name of the ability with no arguments. -If it is an array, the first position of the array will be the name of the ability, and the others will be the arguments +If it is an array, the first position of the array will be the name of the ability, and the others will be the arguments Examples: -`{!! Field::text('change-password', ['allows' => 'change-password']) !!}` -`{!! Field::select('category', $options, ['allows' => ['change-post-category', $category]]) !!}` +```blade +{!! Field::text('change-password', ['allows' => 'change-password']) !!} +``` + +```blade +{!! Field::select('category', $options, ['allows' => ['change-post-category', $category]]) !!} +``` If you are building menus, you can use dynamic parameters to pass values to the gate. In the following example we will define a dynamic 'post' parameter, and pass it using setParam when building the menu: -``` +```php + [ 'view-post' => [], 'edit-post' => [ - 'allows' => ['update-post', ':post'] - ] - ] + 'allows' => ['update-post', ':post'], + ], + ], ]; ``` - -`{!! Menu::make('menu.items')->setParam('post', $post)->render() !}}` - + +```blade +{!! Menu::make('menu.items')->setParam('post', $post)->render() !!} +``` + ## Customization If you are working on a complex project with lots of different access rules, etc. You may need to implement your own AccessHandler, in order to do this, create a new class that implements the `Styde\Html\Access\AccessHandler` interface, then extend the HtmlServiceProvider and override the `registerAccessHandler` method. @@ -86,17 +99,17 @@ If you are working on a complex project with lots of different access rules, etc If you want to use the access handler class as a standalone component, please add this global alias in `config/app.php` -``` - 'aliases' => [ - // ... - 'Access' => Styde\Html\Facades\Access, - // ... - ], +```php + 'aliases' => [ + // ... + 'Access' => Styde\Html\Facades\Access, + // ... + ], ``` Then you can use the facade wherever you want: -``` +```blade @if (Access:check(['roles' => ['admin, 'editor']]))
id]) }}'>
@@ -110,12 +123,15 @@ Then you can use the facade wherever you want:
You can deactivate this component in the configuration:
-```
+```php
+ true,
//..
];
```
-By doing this, the callback, logged and roles attributes will simply be ignored and all users will be able to see all items.
\ No newline at end of file
+
+By doing this, the callback, logged and roles attributes will simply be ignored and all users will be able to see all items.
diff --git a/docs/alert-messages.md b/docs/alert-messages.md
index c2d2679..dd8f210 100644
--- a/docs/alert-messages.md
+++ b/docs/alert-messages.md
@@ -2,38 +2,42 @@
This component will allow you to generate complex alert messages.
- ```
- Alert::info('Your account is about to expire')
- ->details('Renew now to learn about:')
- ->items([
- 'Laravel',
- 'PHP,
- 'And more',
- ])
- ->button('Renew now!', '#', 'primary');
+ ```php
+Alert::info('Your account is about to expire')
+ ->details('Renew now to learn about:')
+ ->items([
+ 'Laravel',
+ 'PHP,
+ 'And more',
+ ])
+ ->button('Renew now!', '#', 'primary');
```
The messages will persist in the session until they are presented to the user with:
-`{!! Alert::render() !!}`
+```blade
+{!! Alert::render() !!}
+```
## Create new alert messages
You can generate new alert messages with:
-`{!! Alert::message('This is a message', 'alert-type') !!}`
+```blade
+{!! Alert::message('This is a message', 'alert-type') !!}
+```
The first argument is the text of the message, and the second one is the type of alert.
For example:
-```
+```php
Alert::message('The end is near', 'danger');
```
You can also use magic methods, the name of the method then becomes the alert type:
-```
+```php
Alert::success("It's all good now");
```
@@ -45,19 +49,25 @@ You can specify more options by method chaining:
You can pass a more detailed message chaining the details() method:
-`{!! Alert::info('Some info')->details('A more detailed explanation goes here') !!}`
+```blade
+{!! Alert::info('Some info')->details('A more detailed explanation goes here') !!}
+```
### call to actions
You can assign buttons to an alert message:
-`{!! Alert::info()->button('Call to action', 'some-url', 'primary') !!}`
+```blade
+{!! Alert::info()->button('Call to action', 'some-url', 'primary') !!}
+```
### html
You can directly pass HTML to the alert message
-`{!! Alert::info()->html('HTML goes here') !!}`
+```blade
+{!! Alert::info()->html('HTML goes here') !!}
+```
Be careful since this won't be escaped
@@ -65,24 +75,37 @@ Be careful since this won't be escaped
You can even render a partial inside an alert message:
-`{!! Alert::info()->view('partials/alerts/partial') !!}`
+```blade
+{!! Alert::info()->view('partials/alerts/partial') !!}
+```
### items
You can pass an array of items (maybe an error list):
-`{!! Alert::danger('Please fix these errors')->items($errors) !!}`
+```blade
+{!! Alert::danger('Please fix these errors')->items($errors) !!}
+```
## Persist alert messages
-Add the following middleware to the `$middleware` array in `app/Http/Kernel.php` **BEFORE** the `\App\Http\Middleware\EncryptCookies`:
+Add the following middleware to the `$middleware` array in `app/Http/Kernel.php` **BEFORE** the `\App\Http\Middleware\EncryptCookies`:
-```
-protected $middleware = [
- //...
- \Styde\Html\Alert\Middleware::class
+```php
+ false
+ 'translate_texts' => false,
//...
];
```
@@ -108,8 +133,12 @@ return [
By default, the alert messages will be rendered with the default template, located in themes/[theme]/alert, for example, for the Bootstrap theme that would be:
-`vendor/styde/html/themes/bootstrap/alert.blade.php`
+```bash
+vendor/styde/html/themes/bootstrap/alert.blade.php
+```
You can pass a custom template as the first argument of the render() method, i.e.:
-`{!! Alert::render('partials/custom-alert-template') !!}`
\ No newline at end of file
+```blade
+{!! Alert::render('partials/custom-alert-template') !!}
+```
diff --git a/docs/es/access-handler.md b/docs/es/access-handler.md
index d22d5f3..046b449 100644
--- a/docs/es/access-handler.md
+++ b/docs/es/access-handler.md
@@ -1,6 +1,6 @@
# Access handler
-Algunas veces quieres mostrar o esconder menu items, form fields, etc. para ciertos usuarios, con este componente se puede hacer sin necesidad de condicionales o código boilerplate.
+Algunas veces querrás mostrar o esconder menu items, form fields, etc. para ciertos usuarios, con este componente se puede hacer sin necesidad de condicionales o código boilerplate.
Este paquete incluye una clase `BasicAccessHandler` pero puedes construir tu propia implementación de `AccessHandler`.
@@ -18,33 +18,38 @@ Sólo pasa una de las siguientes opciones como un atributo de campo o valor del
*WARNING*: tomar en cuenta que este paquete sólo evitará que los elementos aparezcan en el frontend, aún se necesita proteger el acceso de backend usando middleware, etc.
-Uso:
+Uso:
-####Form fields
+#### Form fields
-`{!! Field::select('user_id', null, ['roles' => 'admin'])`
+```blade
+{!! Field::select('user_id', null, ['roles' => 'admin']) !!}
+```
-####Menu items
+#### Menu items
-```
+```php
+ [
'account' => [
- 'logged' => true
+ 'logged' => true,
],
'login' => [
- 'logged' => false
+ 'logged' => false,
],
'settings' => [
- 'roles' => 'admin'
- ]
- ]
+ 'roles' => 'admin',
+ ],
+ ],
];
```
-
-`{!! Menu::make('menu.items') !}}`
+
+```blade
+{!! Menu::make('menu.items') !!}
+```
## Autorización y políticas de acceso
@@ -56,47 +61,55 @@ Si es un array, la primera posición del array será el nombre de la habilidad y
Ejemplos:
-`{!! Field::text('change-password', ['allows' => 'change-password']) !!}`
-`{!! Field::select('category', $options, ['allows' => ['change-post-category', $category]]) !!}`
+```blade
+{!! Field::text('change-password', ['allows' => 'change-password']) !!}
+```
+
+```blade
+{!! Field::select('category', $options, ['allows' => ['change-post-category', $category]]) !!}
+```
Si estás contruyendo menús puedes usar parámetros dinámicos para pasar valores a la autorización.
-En el siguiente ejemplo definiremos un parámetro dinámico 'post' y pasarlo usando setParam cuando se construya el menú:
+En el siguiente ejemplo definiremos un parámetro dinámico 'post' y lo pasaremos usando setParam cuando se construya el menú:
-```
+```php
+ [
'view-post' => [],
'edit-post' => [
- 'allows' => ['update-post', ':post']
- ]
- ]
+ 'allows' => ['update-post', ':post'],
+ ],
+ ],
];
```
-
-`{!! Menu::make('menu.items')->setParam('post', $post)->render() !}}`
-
+
+```blade
+{!! Menu::make('menu.items')->setParam('post', $post)->render() !!}
+```
+
## Personalización
-Si estás trabajando en un proyecto complejo con muchas reglas de acceso diferentes, etc. puedes necesitar implementar un AccessHandler propio. Para hacer esto, crea una nueva clase que implemente la interface `Styde\Html\Access\AccessHandler`, entonces extiende el HtmlServiceProvider y sustituye el método `registerAccessHandler`.
+Si estás trabajando en un proyecto complejo con muchas reglas de acceso diferentes, etc. puedes necesitar implementar un AccessHandler propio. Para hacer esto, crea una nueva clase que implemente la interface `Styde\Html\Access\AccessHandler`, entonces extiende el HtmlServiceProvider y sustituye el método `registerAccessHandler`.
## Standalone
Si se quiere usar la clase del access handler como un componente independiente, por favor agrega este alias global en `config/app.php`.
-```
- 'aliases' => [
- // ...
- 'Access' => Styde\Html\Facades\Access,
- // ...
- ],
+```php
+ 'aliases' => [
+ // ...
+ 'Access' => Styde\Html\Facades\Access,
+ // ...
+ ],
```
Luego se puede utilizar la facade donde se quiera:
-```
+```blade
@if (Access:check(['roles' => ['admin, 'editor']]))
id]) }}'>
@@ -106,12 +119,14 @@ Luego se puede utilizar la facade donde se quiera:
@endif
```
-##Desactivar el access handler
+## Desactivar el access handler
Se puede desactivar este componente en la configuración:
-```
+```php
+ false,
diff --git a/docs/es/alert-messages.md b/docs/es/alert-messages.md
index e84faab..b81f5c1 100644
--- a/docs/es/alert-messages.md
+++ b/docs/es/alert-messages.md
@@ -2,113 +2,129 @@
Este componente permitirá generar mensajes de alerta complejos.
- ```
- Alert::info('Su cuenta está a punto de caducar')
- ->details('Renueva ahora para aprender acerca de:')
- ->items([
- 'Laravel',
- 'PHP,
- 'y más',
- ])
- ->button('¡Renueva ahora!', '#', 'primary');
+ ```php
+Alert::info('Su cuenta está a punto de caducar')
+ ->details('Renueva ahora para aprender acerca de:')
+ ->items([
+ 'Laravel',
+ 'PHP,
+ 'y más',
+ ])
+ ->button('¡Renueva ahora!', '#', 'primary');
```
-Los mensajes serán persistentes en el sesión hasta que sean presentados al usuario con:
+Los mensajes serán persistentes en la sesión hasta que sean presentados al usuario con:
-`{!! Alert::render() !!}`
+```blade
+{!! Alert::render() !!}
+```
## Crear un nuevo mensaje de alerta
-Se puede generar un nuevo mensaje de alerta con:
+Se puede generar un nuevo mensaje de alerta con:
-`{!! Alert::message('Este es el mensaje', 'tipo-alerta') !!}`
+```blade
+{!! Alert::message('Este es el mensaje', 'tipo-alerta') !!}
+```
El primer argumento es el texto del mensaje y el segundo es el tipo de alerta.
Por ejemplo:
-```
+```php
Alert::message('El final está cerca', 'danger');
```
También se puede usar métodos mágicos, el nombre del método se convierte en el tipo de alerta:
-```
+```php
Alert::success("Está todo bien ahora");
```
## Encadenamiento de métodos
-Se puede especificar más opciones por encadenamiento de métodos:
+Se pueden especificar más opciones por encadenamiento de métodos:
-###details
+### Details
Se puede pasar uno o más mensajes detallados encadenando el método details():
-`{!! Alert::info('Algo de información')->details('Una explicación más detallada va aquí') !!}`
+```blade
+{!! Alert::info('Algo de información')->details('Una explicación más detallada va aquí') !!}
+```
-###Llamadas de acción
+### Llamadas de acción
-Se puede asignar botones a un mensaje de alerta:
+Se pueden asignar botones a un mensaje de alerta:
-`{!! Alert::info()->button('Llamada de acción', 'alguna-url', 'primary') !!}`
+```blade
+{!! Alert::info()->button('Llamada de acción', 'alguna-url', 'primary') !!}
+```
-###html
+### Html
-Se puede directamente pasar HTML a un mensaje de alerta:
+Se puede pasar directamente HTML a un mensaje de alerta:
-`{!! Alert::info()->html('El HTML va aquí') !!}`
+```blade
+{!! Alert::info()->html('El HTML va aquí') !!}
+```
Tenga cuidado ya que esto no será escapado.
-###view
+### View
Se puede incluso renderizar una vista dentro de un mensaje de alerta:
-`{!! Alert::info()->view('partials/alerts/partial') !!}`
+```blade
+{!! Alert::info()->view('partials/alerts/partial') !!}
+```
-###items
+### Items
Se puede pasar un array de items (tal vez una lista de errores):
-`{!! Alert::danger('Por favor corrija los siguientes errores')->items($errors) !!}`
+```blade
+{!! Alert::danger('Por favor corrija los siguientes errores')->items($errors) !!}
+```
-##Persistir los mensajes de alerta
+## Persistir los mensajes de alerta
-Agrega el siguiente middleware al array `$middleware` en `app/Http/Kernel.php` **ANTES** de `\App\Http\Middleware\EncryptCookies`:
+Agrega el siguiente middleware al array `$middleware` en `app/Http/Kernel.php` **ANTES** de `\App\Http\Middleware\EncryptCookies`:
-```
+```php
protected $middleware = [
//...
- \Styde\Html\Alert\Middleware::class
+ \Styde\Html\Alert\Middleware::class,
//...
];
```
-Se necesita este middleware para persistir los mensajes de alerta después de que se complete cada request.
+Se necesita este middleware para persistir los mensajes de alerta después de que se complete cada request.
-Por defecto, los mensajes de alerta serán persistidos usando el componente session de Laravel. Pero también se puede crear una implementación propia.
+Por defecto, los mensajes de alerta serán persistidos usando el componente session de Laravel. Pero también se puede crear una implementación propia.
## Traducciones
Si la opción `'translate_texts'` está definida como true en la configuración (es true por defecto), el componente de alerta intentará traducir todos los mensajes, utilizando el valor de la llave `$message`, pero si esta llave de idioma no es encontrada, devolverá el string literal.
-
+
Si no se necesita utilizar el componente Traductor, sólo define translate_texts como false en la configuración:
-```
+```php
+ false
+ 'translate_texts' => false,
//...
];
```
## Themes
-Por defecto, los mensajes de alerta serán renderizados con la plantilla predeterminada, localizada en themes/[theme]/alert, por ejemplo, para el tema de Bootstrap theme que sería:
-
-`vendor/styde/html/themes/bootstrap/alert.blade.php`
+Por defecto, los mensajes de alerta serán renderizados con la plantilla predeterminada, localizada en themes/[theme]/alert, por ejemplo, para el tema de Bootstrap theme que sería: `vendor/styde/html/themes/bootstrap/alert.blade.php`
Se puede pasar un plantilla personalizada como el primer argumento del método render(), es decir:
-`{!! Alert::render('partials/custom-alert-template') !!}`
\ No newline at end of file
+```blade
+{!! Alert::render('partials/custom-alert-template') !!}
+```
diff --git a/docs/es/field-builder.md b/docs/es/field-builder.md
index 994c2ff..624bc47 100644
--- a/docs/es/field-builder.md
+++ b/docs/es/field-builder.md
@@ -4,11 +4,15 @@ Este componente permitirá generar el markup completo para los campos del formul
Si has usado antes el componente HTML de Laravel Collective, ya sabes cómo utilizar los conceptos básicos de este componente; simplemente reemplaza el alias “Form” por “Field”, por ejemplo, sustituye:
-`{!! Form::text(‘name’, ‘value’, $attributes) !!}`
+```blade
+{!! Form::text(‘name’, ‘value’, $attributes) !!}
+```
Por esto:
-`{!! Field::text(‘name’, ‘value’, $attributes) !!}`
+```blade
+{!! Field::text(‘name’, ‘value’, $attributes) !!}
+```
Esto generará un campo incluyendo el container, el label, el control y cualquier error asociado con él.
@@ -16,24 +20,30 @@ Los campos serán generado con el markup predeterminado de **Twitter Bootstrap**
Igualmente hay un montón de opciones convenientes:
-##Omitir el argumento value
+## Omitir el argumento value
Si no quieres pasar un argumento value (`null`) pero quiere pasar el array de `$attributes`, se puede saltar el segundo argumento, es decir, esto:
-`{!! Field::text(‘name’, $attributes) !!}`
+```blade
+{!! Field::text(‘name’, $attributes) !!}
+```
Es lo mismo que:
-`{!! Field::text(‘name’, null, $attributes) !!}`
+```blade
+{!! Field::text(‘name’, null, $attributes) !!}
+```
-##Labels:
+## Labels:
-Se puede explicítamente pasar un label a un campo como parte del array de atributos, es decir:
+Se puede pasar explicítamente un label a un campo como parte del array de atributos, es decir:
-`{!! Field::text(’name’, [‘label’ => ‘Full name’]) !!}`
+```blade
+{!! Field::text(’name’, [‘label’ => ‘Full name’]) !!}
+```
-Como una segunda opción, se puede almacenar los labels en la carpeta lang/ con la misma convención usada para almacenar los nombres de los atributos para los errores de validación:
+Como una segunda opción, se puede almacenar los labels en el directorio lang/ con la misma convención usada para almacenar los nombres de los atributos para los errores de validación:
validation.atributos.[nombre_del_atributo].
@@ -43,28 +53,27 @@ Si saltas ambas opciones, entonces FieldBuilder generará un label basado en el
`full_name` se mostrará "Full name" como el label predeterminado.
-##Templates
-
-Por defecto, los campos serán renderizados con la plantilla predeterminada, ubicada en la carpeta [theme]/fields, por ejemplo, para el tema Bootstrap sería:
+## Templates
-`vendor/styde/html/themes/bootstrap/fields/default.blade.php`
+Por defecto, los campos serán renderizados con la plantilla predeterminada, ubicada en la carpeta [theme]/fields, por ejemplo, para el tema Bootstrap sería: `vendor/styde/html/themes/bootstrap/fields/default.blade.php`
-Pero se tiene la opción de personalizar la plantilla usada para un tipo o campo particular:
+Pero se tiene la opción de personalizar la plantilla usada para un tipo o campo particular:
-###Personalizar por tipo
+### Personalizar por tipo
Algunos frameworks de CSS (como Bootstrap) necesitan diferentes markups para distintas tipos de campos, así que para utilizar la configuración que asigna una plantilla diferente a un tipo de campo determinado, se hace algo como esto:
-```
- 'themes' => [
- 'bootstrap' => [
- 'field_templates' => [
- 'checkbox' => 'checkbox',
- 'checkboxes' => 'collection',
- 'radios' => 'collection'
- ],
- //...
- //...
+```php
+'themes' => [
+ 'bootstrap' => [
+ 'field_templates' => [
+ 'checkbox' => 'checkbox',
+ 'checkboxes' => 'collection',
+ 'radios' => 'collection',
+ ],
+ ],
+],
+//...
```
Con esta configuración los campos "checkbox" usarán la plantilla `vendor/styde/html/themes/bootstrap/fields/checkbox.blade.php` por defecto, mientras que los campos "checkboxes" y "radios" utilizará la plantilla `vendor/styde/html/themes/bootstrap/fields/collection.blade.php`.
@@ -73,49 +82,57 @@ Como puedes ver, la configuración es para este theme en específico, ya que cad
Nota: sólo tienes que preocuparte por el theme que realmente necesitas, por lo que si no planeas usar Bootstrap, puedes borrar/omitir la configuración `bootstrap`
-###Personalizar un campo determinado
+### Personalizar un campo determinado
Puedes especificar una `template` personalizada para un solo campo a través de `'template key'` del array `$attributes`, así:
-`{!! Field::text(’name’, [’template’ => ’templates/my_template’]) !!}`
+```blade
+{!! Field::text(’name’, [’template’ => ’templates/my_template’]) !!}
+```
La ruta será relativa al directorio resources/views/
-###Personalización de plantillas predeterminadas
+### Personalización de plantillas predeterminadas
Si quieres personalizar las plantillas predeterminadas, sólo ejecuta `php artisan vendor:publish` en la consola y todas las plantillas serán copiadas a la carpeta `resources/views/themes/[theme]/fields/`
De otra manera, el paquete usará las plantillas predeterminadas (almacenadas en `/vendor/styde/html/themes/`) y no será necesario copiar archivos adicionales dentro del proyecto.
-##Atributo name
+## Atributo name
Puedes usar la notación de punto como nombre del campo, por ejemplo: `profile.twitter` y se transformará a `profile[twitter]`
-##Atributo id
+## Atributo id
Éste se asignará automáticamente para control de cada input, si utilizas la notación de punto (ejemplo: user.name) los puntos serán reemplazados por guiones bajos (ejemplo: user_name)
-##Atributo required
+## Atributo required
Puedes especificar un valor 'required' en el array de atributos:
-`{!! Field::text(’name’, [’required’]) !!}`
+```blade
+{!! Field::text(’name’, [’required’]) !!}
+```
O como un par llave => valor (el campo será marcado como `required` si el valor se evalúa como true, es decir:
-`$required = true;`
+```php
+$required = true;
+```
-`{!! Field::text(’name’, null, [’required’ => $required]) !!}`
+```blade
+{!! Field::text(’name’, null, [’required’ => $required]) !!}
+```
Las plantillas de campo siempre tendrán una variable `required` por lo que pueda ser usado para imprimir clases de CSS adicionales o badges, para indicar si un campo es necesario u opcional, es decir:
-```
- @if ($required)
- Required
- @endif
+```blade
+@if ($required)
+ Required
+@endif
```
-##Errores:
+## Errores:
Cualquier error de sesión será cargado en el FieldBuilder a través de `HtmlServiceProvider` y se tendrá `$errors` específicos por cada campo disponible en la plantilla, también se tendrá una variable `$hasErrors` en caso que el campo tenga algún error y se necesite imprimir una clase de CSS adicional, etc.
@@ -123,48 +140,62 @@ Por ejemplo, con Twitter Bootstrap se necesitará una clase `has-error` en caso
Este es un extracto de una plantilla personalizada para el theme Bootstrap:
-` `
-en vez de esto:
+en vez de así:
-` `
+` `
-Si ninguna clase es evaluada como TRUE entonces esta función retornará una cadena vacía.
+Si ninguna clase es evaluada como `true` entonces esta función retornará una cadena vacía.
diff --git a/docs/es/internationalization.md b/docs/es/internationalization.md
index ddb6812..aa99213 100644
--- a/docs/es/internationalization.md
+++ b/docs/es/internationalization.md
@@ -2,11 +2,13 @@
Puedes configurar si quieres usar este paquete para tratar de traducir los textos o no, por ejemplo si tu proyecto sólo necesita ser implementado en un idioma y prefieres simplemente escribir los textos donde los necesites en lugar de utilizar el componente Translator, desactiva las traducciones en la configuración:
-```
+```php
+ false
+ 'translate_texts' => false,
//...
];
```
@@ -18,20 +20,23 @@ Pero si tu proyecto necesita ser implementado en más de un idioma o quieres org
## Traducir labels (field builder)
Si quieres tener un label específico en un campo, puedes hacerlo pasándolo como parte del array de atributos:
-
- `{!! Field::text('name', ['label' => 'Nombre completo']) !!}`
-
+
+```blade
+{!! Field::text('name', ['label' => 'Nombre completo']) !!}
+```
+
También puedes definirlo como parte del array `attributes`en el archivo `resources/lang/en/validation.php`:
-
- ```
- //resources/lang/en/validation.php
- //..
- 'attributes' => [
- 'name' => 'Nombre completo'
- ],
+
+```php
+//resources/lang/en/validation.php
+
+//..
+'attributes' => [
+ 'name' => 'Nombre completo',
+],
```
-Toma en cuenta que esto también es una convención usada por el componente Laravel Validator, de esta manera puedes tener todos los textos de los labels en un mismo lugar.
+Toma en cuenta que esto también es una convención usada por el componente Laravel Validator, de esta manera puedes tener todos los textos de los labels en un mismo lugar.
[Aprender más sobre field builder](field-builder.md)
@@ -39,9 +44,9 @@ Toma en cuenta que esto también es una convención usada por el componente Lara
Si `'translate_texts'` es definido como `true`, este componente asumirá que todos los mensajes de alerta son de hecho llaves de idioma e intentará traducirlas. Es decir, puedes hacer cosas como:
-```
+```php
Alert::success('messages.users.updated')
- ->button('messages.users.go_to_profile', url('users/profile'))
+ ->button('messages.users.go_to_profile', url('users/profile'))
```
Por supuesto, si la llave de idioma no es encontrada, éste devolverá el string literal (también puesdes pasar el mensaje completo en lugar de una llave de idioma).
@@ -52,29 +57,35 @@ Por supuesto, si la llave de idioma no es encontrada, éste devolverá el string
Si `'translate_texts'` es definido como `true`, pero no específicas un título explícito para un menu item; el componente buscará un llave de idioma en: `menu.[llave_menu_item]` si la llave no es encontrada, el paquete intentará convertir la llave del menu item en un formato de título. Por ejemplo:
-```
+```php
+ 'Homepage'
+ 'home' => 'Homepage',
];
```
-```
+```php
+ [
'home' => [],
'about' => ['title' => 'Who we are'],
- 'contact-us' => []
- ]
+ 'contact-us' => [],
+ ],
];
```
-`{!! Menu::make('menu.items') !!}`
+```blade
+{!! Menu::make('menu.items') !!}
+```
Devolverá algo así:
-```
+```html
`
+```blade
+
+```
instead of this:
-` `
+```blade
+
+```
-If no classes are evaluated as TRUE then this function will return an empty string.
\ No newline at end of file
+If no classes are evaluated as TRUE then this function will return an empty string.
diff --git a/docs/internationalization.md b/docs/internationalization.md
index 800d528..1becd15 100644
--- a/docs/internationalization.md
+++ b/docs/internationalization.md
@@ -2,12 +2,14 @@
You can configure whether you want this package to attempt to translate texts or not, for example if your project only needs to implement one language and you prefer to simply write texts wherever you need them instead of using the Translator component, please deactivate translations in the configuration:
-```
+```php
+ false
- //...
+ //...
+ 'translate_texts' => false,
+ //...
];
```
@@ -18,20 +20,26 @@ But if your project needs to implement more than one language or you want to org
## Translating labels (field builder)
If you want to have a specific label in a field, you can do so by passing it as part of the attribute array:
-
- `{!! Field::text('name', ['label' => 'Full name']) !!}`
-
+
+```blade
+{!! Field::text('name', ['label' => 'Full name']) !!}
+```
+
But you can also define it as part of the `attributes` array in the `resources/lang/en/validation.php` file:
-
- ```
- //resources/lang/en/validation.php
- //..
- 'attributes' => [
- 'name' => 'Full name'
- ],
+
+```php
+ [
+ 'name' => 'Full name'
+ ],
+];
```
-Note that this is also the convention used by the Laravel Validator component, so this way you can have all your label texts in one place.
+Note that this is also the convention used by the Laravel Validator component, so this way you can have all your label texts in one place.
[Learn more about the field builder](field-builder.md)
@@ -39,10 +47,11 @@ Note that this is also the convention used by the Laravel Validator component, s
If the `'translate_texts'` is set to `true`, this component will assume that all the alert messages are in fact language keys and will try to translate them. This means you can do things like this:
-```
+```php
Alert::success('messages.users.updated')
- ->button('messages.users.go_to_profile', url('users/profile'))
+ ->button('messages.users.go_to_profile', url('users/profile'))
```
+
Of course if the lang key is not found, it will return the literal string (so you can also pass the full message instead of a lang key).
[Learn more about the alert component](alert-messages.md)
@@ -51,29 +60,34 @@ Of course if the lang key is not found, it will return the literal string (so yo
If the `'translate_texts'` is set to `true`, and you don't specify an explicit title for a menu item; the component will search for a lang key in: `menu.[menu_item_key]` if the key is not found, the package will attempt to convert the menu item key in a title format. For example:
-```
+```php
+ 'Homepage'
+ 'home' => 'Homepage',
];
```
-```
+```php
//config/menu.php
+
return [
'items' => [
'home' => [],
'about' => ['title' => 'Who we are'],
- 'contact-us' => []
- ]
+ 'contact-us' => [],
+ ],
];
```
-`{!! Menu::make('menu.items') !!}`
+```blade
+{!! Menu::make('menu.items') !!}
+```
Will return something like:
-```
+```html