- Стилизация интерфейса с помощью Webpack
- Использование Sass
- Эффективное использование Bootstrap
- Стилизация HTML-шаблона
- Сборка ресурсов
- Styling the User Interface with Webpack
- Using Sass
- Leveraging Bootstrap
- Styling the HTML
- Building Assets
- Introduction
- Webpack Encore
- Encore Documentation
- Getting Started
- Using Bootstrap CSS & JS
- Importing Bootstrap Styles
- Importing Bootstrap JavaScript
- Using Bootstrap with Turbo
- Using other Bootstrap / jQuery Plugins
Стилизация интерфейса с помощью Webpack
До сих пор мы совсем не занимались дизайном пользовательского интерфейса. Для оформления интерфейса, как подобает настоящему профессионалу, воспользуемся современным стеком технологий при помощи Webpack. А чтобы быть ближе к Symfony и как можно проще интегрировать Webpack в наше приложение, установим Webpack Encore:
$ symfony composer req encore
Теперь у нас есть полноценная среда для работы Webpack: сгенерированы файлы package.json и webpack.config.js с уже рабочими настройкам по умолчанию. Откройте файл webpack.config.js , который использует Encore, чтобы настроить Webpack.
В файле package.json есть несколько полезных команд, которые мы будем использовать на протяжении всей книги.
Директория assets содержит главные точки входа ресурсов в проекте: styles/app.css и app.js .
Использование Sass
Вместо обычного CSS давайте воспользуемся Sass:
$ mv assets/styles/app.css assets/styles/app.scss
--- a/assets/app.js +++ b/assets/app.js @@ -6,7 +6,7 @@ */ // any CSS you import will output into a single css file (app.css in this case) -import './styles/app.css'; +import './styles/app.scss'; // start the Stimulus application import './bootstrap';
Установите загрузчик Sass:
$ npm install node-sass sass-loader --save-dev
А затем включите Sass в конфигурации webpack:
--- a/webpack.config.js +++ b/webpack.config.js @@ -57,7 +57,7 @@ Encore >) // enables Sass/SCSS support - //.enableSassLoader() + .enableSassLoader() // uncomment if you use TypeScript //.enableTypeScriptLoader()
Как я узнал, какие пакеты нужно установить? При попытке собрать ресурсы без необходимых пакетов, Encore вернул бы нам сообщение об ошибке и предложил бы выполнить команду npm install , чтобы установить зависимости для обработки файлов с расширением .scss .
Эффективное использование Bootstrap
В создании адаптивного сайта, особенно в самом начале разработки, такой CSS-фреймворк как Bootstrap, может значительно помочь. Установите его как пакет:
$ npm install bootstrap @popperjs/core bs-custom-file-input --save-dev
Теперь подключите Bootstrap в следующем CSS-файле (предварительно очистив его):
--- a/assets/styles/app.scss +++ b/assets/styles/app.scss @@ -1,3 +1 @@ -body - background-color: lightgray; -> +@import '~bootstrap/scss/bootstrap';
То же самое нужно сделать в JS-файле:
1 2 3 4 5 6 7 8 9 10 11 12 13
--- a/assets/app.js +++ b/assets/app.js @@ -7,6 +7,10 @@ // any CSS you import will output into a single css file (app.css in this case) import './styles/app.scss'; +import 'bootstrap'; +import bsCustomFileInput from 'bs-custom-file-input'; // start the Stimulus application import './bootstrap'; + +bsCustomFileInput.init();
У форм в Symfony есть встроенная поддержка Bootstrap со специальной темой, включите её:
twig: form_themes: ['bootstrap_5_layout.html.twig']
Стилизация HTML-шаблона
Теперь всё готово, чтобы непосредственно перейти к оформлению внешнего вида приложения. Скачайте и распакуйте архив в корневой директории проекта:
$ php -r "copy('https://symfony.com/uploads/assets/guestbook-6.2.zip', 'guestbook-6.2.zip');" $ unzip -o guestbook-6.2.zip $ rm guestbook-6.2.zip
Изучите код шаблонов, возможно, вы узнаете кое-что новое о Twig.
Сборка ресурсов
Один важный момент при использовании Webpack — CSS- и JS-файлы не могут использоваться напрямую в приложении. Перед этим их сначала нужно «скомпилировать».
Собрать ресурсы в процессе разработки можно с помощью команды encore dev :
Чтобы не выполнять эту команду каждый раз после внесения изменений, запустите её в фоновом режиме и оставьте наблюдать за изменениями JS и CSS:
$ symfony run -d npm run watch
Остановитесь на минутку и изучите изменения внешнего вида. Посмотрите на новый дизайн в браузере.
Теперь ранее сгенерированная форма входа имеет оформление, потому что бандл Maker по умолчанию использует CSS-классы из Bootstrap:
В продакшен-окружении Platform.sh автоматически определит, что в проекте используется Encore и поэтому автоматически во время сборки приложения скомпилирует все его ресурсы.
Styling the User Interface with Webpack
We have spent no time on the design of the user interface. To style like a pro, we will use a modern stack, based on Webpack. And to add a Symfony touch and ease its integration with the application, let’s use Webpack Encore:
$ symfony composer req encore
A full Webpack environment has been created for you: package.json and webpack.config.js have been generated and contain good default configuration. Open webpack.config.js , it uses the Encore abstraction to configure Webpack.
The package.json file defines some nice commands that we will use all the time.
The assets directory contains the main entry points for the project assets: styles/app.css and app.js .
Using Sass
Instead of using plain CSS, let’s switch to Sass:
$ mv assets/styles/app.css assets/styles/app.scss
--- a/assets/app.js +++ b/assets/app.js @@ -6,7 +6,7 @@ */ // any CSS you import will output into a single css file (app.css in this case) -import './styles/app.css'; +import './styles/app.scss'; // start the Stimulus application import './bootstrap';
$ npm install node-sass sass-loader --save-dev
And enable the Sass loader in webpack:
--- a/webpack.config.js +++ b/webpack.config.js @@ -57,7 +57,7 @@ Encore >) // enables Sass/SCSS support - //.enableSassLoader() + .enableSassLoader() // uncomment if you use TypeScript //.enableTypeScriptLoader()
How did I know which packages to install? If we had tried to build our assets without them, Encore would have given us a nice error message suggesting the npm install command needed to install dependencies to load .scss files.
Leveraging Bootstrap
To start with good defaults and build a responsive website, a CSS framework like Bootstrap can go a long way. Install it as a package:
$ npm install bootstrap @popperjs/core bs-custom-file-input --save-dev
Require Bootstrap in the CSS file (we have also cleaned up the file):
--- a/assets/styles/app.scss +++ b/assets/styles/app.scss @@ -1,3 +1 @@ -body - background-color: lightgray; -> +@import '~bootstrap/scss/bootstrap';
Do the same for the JS file:
1 2 3 4 5 6 7 8 9 10 11 12 13
--- a/assets/app.js +++ b/assets/app.js @@ -7,6 +7,10 @@ // any CSS you import will output into a single css file (app.css in this case) import './styles/app.scss'; +import 'bootstrap'; +import bsCustomFileInput from 'bs-custom-file-input'; // start the Stimulus application import './bootstrap'; + +bsCustomFileInput.init();
The Symfony form system supports Bootstrap natively with a special theme, enable it:
twig: form_themes: ['bootstrap_5_layout.html.twig']
Styling the HTML
We are now ready to style the application. Download and expand the archive at the root of the project:
$ php -r "copy('https://symfony.com/uploads/assets/guestbook-6.2.zip', 'guestbook-6.2.zip');" $ unzip -o guestbook-6.2.zip $ rm guestbook-6.2.zip
Have a look at the templates, you might learn a trick or two about Twig.
Building Assets
One major change when using Webpack is that CSS and JS files are not usable directly by the application. They need to be «compiled» first.
In development, compiling the assets can be done via the encore dev command:
Instead of executing the command each time there is a change, send it to the background and let it watch JS and CSS changes:
$ symfony run -d npm run watch
Take the time to discover the visual changes. Have a look at the new design in a browser.
The generated login form is now styled as well as the Maker bundle uses Bootstrap CSS classes by default:
For production, Platform.sh automatically detects that you are using Encore and compiles the assets for you during the build phase.
Introduction
Symfony gives you the flexibility to choose any front-end tools you want. This could be dead-simple — like putting CSS & JS directly in the public/ directory — or more advanced — like scaffolding your front-end with a tool like Next.js.
However, Symfony does come with two powerful options to help you build a modern, fast frontend, and enjoy the process:
- Webpack Encore is a powerful tool built with Node.js on top of Webpack that allows you to write modern CSS & JavaScript and handle things like JSX (React), Vue or TypeScript.
- AssetMapper, is a production-ready simpler alternative to Webpack Encore that runs entirely in PHP. It’s currently experimental.
Encore | AssetMapper | |
---|---|---|
Production Ready? | yes | yes |
Stable? | yes | experimental |
Requirements | Node.js | none: pure PHP |
Requires a build step? | yes | no |
Works in all browsers? | yes | yes |
Supports Stimulus/UX | yes | yes |
Supports Sass/Tailwind | yes | yes |
Supports React, Vue, Svelte? | yes | yes [#1]_ |
Supports TypeScript | yes | no [#1]_ |
Webpack Encore
Do you prefer video tutorials? Check out the Webpack Encore screencast series.
Webpack Encore is a simpler way to integrate Webpack into your application. It wraps Webpack, giving you a clean & powerful API for bundling JavaScript modules, pre-processing CSS & JS and compiling and minifying assets. Encore gives you a professional asset system that’s a delight to use.
Encore is inspired by Webpacker and Mix, but stays in the spirit of Webpack: using its features, concepts and naming conventions for a familiar feel. It aims to solve the most common Webpack use cases.
Encore is made by Symfony and works beautifully in Symfony applications. But it can be used in any PHP application and even with other server-side programming languages!
Encore Documentation
Getting Started
Using Bootstrap CSS & JS
This article explains how to install and integrate the Bootstrap CSS framework in your Symfony application using Webpack Encore. First, to be able to customize things further, we’ll install bootstrap :
# if you use the Yarn package manager $ yarn add bootstrap --dev # if you use the npm package manager $ npm install bootstrap --save-dev
Importing Bootstrap Styles
Now that bootstrap lives in your node_modules/ directory, you can import it from any Sass or JavaScript file. For example, if you already have a global.scss file, import it from there:
// assets/styles/global.scss // customize some Bootstrap variables $primary: darken(#428bca, 20%); // the ~ allows you to reference things in node_modules @import "~bootstrap/scss/bootstrap";
That’s it! This imports the node_modules/bootstrap/scss/bootstrap.scss file into global.scss . You can even customize the Bootstrap variables first!
If you don’t need all of Bootstrap’s features, you can include specific files in the bootstrap directory instead — e.g. ~bootstrap/scss/alert .
Importing Bootstrap JavaScript
First, install the JavaScript dependencies required by the Bootstrap version used in your application:
# if you use the Yarn package manager # (jQuery is only required in versions prior to Bootstrap 5) $ yarn add jquery @popperjs/core --dev # if you use the npm package manager # (jQuery is only required in versions prior to Bootstrap 5) $ npm install jquery @popperjs/core --save-dev
Now, require bootstrap from any of your JavaScript files:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// app.js const $ = require('jquery'); // this "modifies" the jquery module: adding behavior to it // the bootstrap module doesn't export/return anything require('bootstrap'); // or you can include specific pieces // require('bootstrap/js/dist/tooltip'); // require('bootstrap/js/dist/popover'); $(document).ready(function( ) < $('[data-toggle="popover"]').popover(); >);
Using Bootstrap with Turbo
If you are using bootstrap with Turbo Drive, to allow your JavaScript to load on each page change, wrap the initialization in a turbo:load event listener:
// app.js // this waits for Turbo Drive to load document.addEventListener('turbo:load', function (e) < // this enables bootstrap tooltips globally let tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]')) let tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) < return new Tooltip(tooltipTriggerEl) >); >);
Using other Bootstrap / jQuery Plugins
If you need to use jQuery plugins that work well with jQuery, you may need to use Encore’s autoProvidejQuery() method so that these plugins know where to find jQuery. Then, you can include the needed JavaScript and CSS like normal:
// . // require the JavaScript require('bootstrap-star-rating'); // require 2 CSS files needed require('bootstrap-star-rating/css/star-rating.css'); require('bootstrap-star-rating/themes/krajee-svg/theme.css');