Layer | Tool | Environment |
---|---|---|
Frontend | Foundation for Emails (Includes: Handlebars, Panini, Inky, Sass, Browsersync, Gulp) |
Nodejs <= 10 npm <= 6 |
Установка зависимостей строго на Nodejs 10 через npm
# Clone via HTML
git clone https://github.com/ncer/foundation-emails-template.git projectname
# Or clone via SSH
git clone git@github.com:ncer/foundation-emails-template.git projectname
# Install Nodejs 10 via NVM
nvm install 10
nvm use 10
# Install project dependencies via NPM
cd projectname
npm install
- Добавлена переменная
global.cdn
(см.src/data/global.js
) для указаня хоста CDN'а, куда предположительно будет копироваться содержимое папкиdist
. - Реализован сброс кэша через добавление версии ко всем ресурсам на случай, если CDN кеширует слишком жестко (используется переменная
timestamp
вsrc/data/global.js
). - Добавлены полезные Handlebars хелперы (см.
src/helpers
) и Sass миксины (см.src/assets/scss/template/_mixins.scss
), в том числе для удобной работы с CDN и кэшем. Также добавлены классы для работы со светлой и темной темами (см.src/assets/scss/template/_theme.scss
) - Добавлена команда
npm run inline
. Делает то же, что иnpm start
, но c инлайном CSS стилей в HTML и минификацией. Полезно периодически запускать и чекать верстку перед билдом. - С главной страницы теперь можно не только открыть HTML письма, но и скачать zip-архив (должен быть предварительно сгенерирован командой
npm run zip
). К главной странице не применяется инлайн стилей, она не пакуется в архив и не отсылается на почту (при запускеnpm run mail
/npm run litmus
). - Для отправки тестовых писем через
npm run mail
больше не обязателен конфиг AWS. Достаточно сконфигурировать секциюmail
вconfig.json
(предварительно нужно его создать, примеры полей см. вexample.config.json
).
Handlebars хелпер для изображений (CDN + сброс кэша)
<img src="{{imgUrl 'assets/img/fake-logo.png'}}">
Sass миксин для изображений (CDN + сброс кэша)
@import "mixins";
.zurb {
background-image: img-url('../assets/img/zurb.png');
}
Использование изображений для темной темы в Handlebars (комментарии обязательны!)
<img src="{{imgUrl 'assets/img/vk.png'" class="light-theme" />
<!--[if !mso]><!-->
<img src="{{imgUrl 'assets/img/dark-theme/vk.png'" class="dark-theme" />
<!--<![endif]-->
Использование изображений для темной темы в Sass
@import "mixins";
.vk {
background-image: img-url('../assets/img/vk.png');
@include dark-theme() {
background-image: img-url('../assets/img/dark-theme/vk.png') !important;
}
}
Достаточно много советов по верстке описано в документации фреймворка.
К этому списку можно еще добавить:
- Верстать нужно строго от десктопа к мобиле, т.е.
@media min-width
— нельзя, а@media max-width
— можно. Напр., android-клиент Яндекс Почты выпиливает медиа запросы (точнее тег<style>
, в котором они лежат) и просто масштабирует десктопную версию письма. Стало быть, если стили десктопной версии будут обернуты в@media min-width
, то в письме вообще никаких стилей не окажется! Запрос@media max-width
в этом плане лучше, потому что работает как прогрессивное улучшение для клиентов, которые его поддерживают (напр., Gmail). - Повышать приоритет селекторов в десктопной версии можно только путем увеличения их специфичности. Использовать для этого
!important
нельзя! Напр., приложение Почта на Windows 10 (по сути потомок Outlook) беспощадно выпиливает все CSS свойства с ключевым словом!important
. - Вертикальное вырванивание двух и более элементов в строке лучше делать таблицами. Напр., Почта на Windows 10 не переварит попытку выравнивания через
display: inline[-block]
+vertical-align: middle
. О флексах вообще забудьте, о чем вы. - Ссылки всегда должны быть абсолютными и с обязательным указанием протокола
http[s]://
. Напр., веб-версия Outlook беспощадно выпиливает абсолютные ссылки без протокола//example.com
.
Please open all issues with this template on the main Foundation for Emails repo.
This is the official starter project for Foundation for Emails, a framework for creating responsive HTML devices that work in any email client. It has a Gulp-powered build system with these features:
- Handlebars HTML templates with Panini
- Simplified HTML email syntax with Inky
- Sass compilation
- Image compression
- Built-in BrowserSync server
- Full email inlining process
To use this template, your computer needs Node.js 0.12 or greater. The template can be installed with the Foundation CLI, or downloaded and set up manually.
Install the Foundation CLI with this command:
npm install foundation-cli --global
Use this command to set up a blank Foundation for Emails project:
foundation new --framework emails
The CLI will prompt you to give your project a name. The template will be downloaded into a folder with this name.
To manually set up the template, first download it with Git:
git clone https://github.com/zurb/foundation-emails-template projectname
Then open the folder in your command line, and install the needed dependencies:
cd projectname
npm install
Run npm start
to kick off the build process. A new browser tab will open with a server pointing to your project files.
Run npm run build
to inline your CSS into your HTML along with the rest of the build process.
Run npm run litmus
to build as above, then submit to litmus for testing. AWS S3 Account details required (config.json)
Run npm run mail
to build as above, then send to specified email address for testing. SMTP server details required (config.json)
Run npm run zip
to build as above, then zip HTML and images for easy deployment to email marketing services.
If you create a lot of emails, your build can start to slow down, as each build rebuilds all of the emails in the
repository. A simple way to keep it fast is to archive emails you no longer need by moving the pages into src/pages/archive
.
You can also move images that are no longer needed into src/assets/img/archive
. The build will ignore pages and images that
are inside the archive folder.
Testing in Litmus requires the images to be hosted publicly. The provided gulp task handles this by automating hosting to an AWS S3 account. Provide your Litmus and AWS S3 account details in the example.config.json
and then rename to config.json
. Litmus config, and aws.url
are required, however if you follow the aws-sdk suggestions you don't need to supply the AWS credentials into this JSON.
{
"aws": {
"region": "us-east-1",
"accessKeyId": "YOUR_ACCOUNT_KEY",
"secretAccessKey": "YOUR_ACCOUNT_SECRET",
"params": {
"Bucket": "elasticbeanstalk-us-east-1-THIS_IS_JUST_AN_EXAMPLE"
},
"url": "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-THIS_IS_JUST_AN_EXAMPLE"
},
"litmus": {
"username": "YOUR_LITMUS@EMAIL.com",
"password": "YOUR_ACCOUNT_PASSWORD",
"url": "https://YOUR_ACCOUNT.litmus.com",
"applications": ["ol2003","ol2007","ol2010","ol2011","ol2013","chromegmailnew","chromeyahoo","appmail9","iphone5s","ipad","android4","androidgmailapp"]
}
}
Similar to the Litmus tests, you can have the emails sent to a specified email address. Just like with the Litmus tests, you will need to provide AWS S3 account details in config.json
. You will also need to specify to details of an SMTP server. The email address to send to emails to can either by configured in the package.json
file or added as a parameter like so: npm run mail -- --to="example.com"
{
"aws": {
"region": "us-east-1",
"accessKeyId": "YOUR_ACCOUNT_KEY",
"secretAccessKey": "YOUR_ACCOUNT_SECRET",
"params": {
"Bucket": "elasticbeanstalk-us-east-1-THIS_IS_JUST_AN_EXAMPLE"
},
"url": "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-THIS_IS_JUST_AN_EXAMPLE"
},
"mail": {
"to": [
"example@domain.com"
],
"from": "Company name <info@company.com",
"smtp": {
"auth": {
"user": "example@domain.com",
"pass": "12345678"
},
"host": "smtp.domain.com",
"secureConnection": true,
"port": 465
}
}
}
For a full list of Litmus' supported test clients(applications) see their client list.
Caution: AWS Service Fees will result, however, are usually very low do to minimal traffic. Use at your own discretion.