The following is a guest post by Pascal Klau, a trainee from South Germany, who dislikes unnecessary HTTP requests and broccoli. Pascal is going to explain way to use a polyfilling service in such a way that you might get away with not using it at all.
The Situation
We want to write JavaScript in the ES6 syntax. But since we need to support older browsers that don’t understand ES6, we need to deal with that.
Here the standard procedure: Write ES6 ? compile everything down to ES5 (e.g. Babel) ? send that to the browser.
This may not be the most efficient way anymore. The problem is that we’re forcing modern browsers to run the old code when they don’t have to. They support ES6, so can’t we give them ES6.
A Better Way
There is a polyfill project called Polyfill.io API that can polyfill ES6 code client side.
It also implements polyfills for some HTML features like the element.
Description from their website:
Polyfill.io reads the User-Agent (UA) header of each request and returns polyfills that are suitable for the requesting browser. Tailor the response based on the features you’re using in your app […]
It is being developed by Financial Times, so it has some support and we can be fairly confident it’s not going to disappear on us.
One thing to be clear on: Polyfill.io does not provide support for syntactic sugar. For example, Classes, enhanced Object Literals, and things like Arrow Functions. You’d still need a compiler for those.
Set up Polyfill.io
Adding Polyfill.io to your project can be this simple. Add the CDN-hosted script to your page:
Running the script spits out the UA and what features you want.
UA detected: chrome/56.0.0
Features requested: default
Change request parameters
There are a bunch of options to customize the request which you put into the script source.
Features
List of browser features to polyfill. Accepts a comma-separated list of feature names. Available feature names are shown on the Browsers and Features page.
In Safari 10 the script now says something like this:
Features requested: fetch
- setImmediate, License: CC0 (required by "Promise", "fetch")
- fetch
If a feature like fetch depends on another feature like Promise, Polyfill.io automatically adds it.
Flags
always – Polyfill should be included regardless of whether it is required by the user-agent making the request.
gated – If the polyfill is included in the bundle, it will be accompanied by a feature detect, which will only execute the polyfill if the native API is not present.
Name of a function to call after the polyfills are loaded. It is simply a way of triggering your own code when the polyfills have loaded, intended to allow the polyfill service to be more easily loaded asynchronously with async and defer attributes.
The Problem
As good as all this sounds, it is still not perfect.
Modern browsers do not have to load ES5 now, but instead have to make a server roundtrip (an HTTP Request) to check if polyfills are needed.
This bugged me so much that I worked on a little project to help.
An Even Better Way
Set up dynamic polyfill
The npm package I created is called dynamic-polyfill. It checks whether the feature is natively supported or not before making any server request.
That will execute essentially like this, in plain language:
Do [window.fetch, window.Promise] exist?
If they do, run the afterFill() callback.
If they do not, create a tag with async attribute, insert the Polyfill.io link with all the provided options and run the afterFill() callback after it has finished loading.
Note: Not all options are support yet, only the most important ones.
Small footprint
Since this module is less than 1KB minified and does not have any dependencies, it has a super small footprint in your project.
Conclusion
Write future-proof and efficient JavaScript for modern browsers. Let Polyfill.io handle older browsers. Don’t do the extra HTTP Request if you don’t have to.
Just make sure you have something handy to dry these tears of joy.
Say you want an element to be in one state for 9 seconds, and in another state for 1 second, on a loop.
No tweening between the state, just a straight swap.
I was wondering how to go about this other day, and Sarah Drasner showed me that you can use reallllllly short distances between keyframes to move from one state to another. Like 59.999% to 60%. No opportunity to tween there on a normal animation duration like 10 seconds.
Perhaps a little bit cleaner, you don’t even have to get tricky with the .999 stuff if you use steps, like:
div {
...
animation: color 10s steps(10) infinite both;
}
Single keyframe / Single step changer
That led me to stumble into another super weird CSS thing. You’d think if you used steps(1) that no change at all would occur, right? Since there is only one step? Not true, there is actually 2 steps when you use steps(1), for who-knows-what reasoning. We can use that.
Say we were going for the original premise of this article: one state for 9 seconds, and in another state for 1 second. Like this:
1-1-1-1-1-1-1-1-1-2
You could do:
div {
...
background: orangered;
animation: color 10s steps(1) infinite both;
}
@keyframes color {
90% {
background: teal;
}
}
That div will only be teal for 1 second! Then switch back to orangered. Change that keyframe to 70% and you’d get:
We have a pretty cool trick in hand now for changing state in a timed loop. If you didn’t want the looping part, you could have the animation run once and stay there like:
div {
...
background: orangered;
animation: color 10s steps(1) forwards;
}
@keyframes color {
90% {
background: teal;
}
}
All we’ve done here is removed the infinite keyword which was making it repeat, and used forwards meaning “when it gets to the end, keep the styles in that final state”. (The both keyword will do that too.)
But how do you swap from one state to another from a user interaction? Even this is possible! Imagine an animation with a super long duration (like, days and days). You could tie a user interaction to jumping around positions (state) within that. Here’s a simple demo of that where the clicking of a link triggers a :target state, which triggers an animation to jump to a position within keyframes that style that state:
Center Your Logo Vertically and Horizontally Within the Browser in Adobe Muse. No Coding Skills Required.
Branding plays a big part in web design and most websites are branded with a logo and a slogan. A lot of times web designers and developers look for the best way to initially show the brand when someone visits their website. That is why I decided to create the Browser Centering Widget. With this widget you can initially center any element directly in the center of the browser. The element will be vertically centered and horizontally centered across all devices until the user scrolls, and then the element scrolls with the website. You can also fix the element in the center of the browser. This will insure that the brand or logo gets maximum attention and looks great when the user first visits the website. In the video above I go over how to use the Browser Centering Widget in your Adobe Muse website.
The steps are as follows:
1. Drag and drop the widget from the library panel onto your Adobe Muse website. If you do not see the library panel go to Window > Library.
2. Assign the graphic style name that is in the widget to the element you would like to center via the graphic styles panel. If you do not see the graphic styles panel go to Window > Graphic Styles.
3. Place the element at the very top of your Adobe Muse website. Element can be anywhere at the top.
4. If you would like the element to stay fixed in the center and not scroll with the website select ‘Fixed in Center’ within the widget.
5. Done.
You now have a centered element on your website. No matter what device the user is on you can be sure that the centered element will be the first thing they see.
When I was a developer, I often had a hundred questions when building websites from wireframes that I had received. Some of those questions were, “How will this design scale when I shrink the browser window?” and, “What happens when this shape is filled out incorrectly?” and even, “What are the options in this sorting filter, and what do they do?”
These types of questions led me to miss numerous deadlines, and I wasted time and energy in back-and-forth communication. Sadly, this situation could have been avoided if the wireframes had provided enough detail.
Design teams are usually made up of individuals having diverse yet complementary skills. Under proper leadership, they can do what is needed to ensure a project’s success. If not applied properly however, the skills they bring to the table can undermine the chances of a project’s success.
A team leader’s role, is to take these individual team members, and mold them into a cohesive group that will work together toward a common goal.
The team leader’s job can become much easier. How? By choosing tools to help manage the workflow, and encourage collaboration among team members. Yet, even the best tools can’t do it all. The team leader needs to play a proactive role in getting the team working together and focused on a common aim. The following key issues must be addressed for that to happen:
Constantly clarify roles. If roles are not clear, or allowed to overlap; oversights, duplication of effort, and/or confusion will likely result.
Explicitly state team member responsibilities. Responsibilities are best assigned to individuals rather than groups to ensure things get done.
Identify who is responsible for making a specific decision. If more than one person is responsible, how decisions will be reached needs to be spelled out.
Continuously review team and project goals. This ensures that everyone will be focused on the tasks at hand.
Use pre-selected tools for specific functions. This ensures the right tools are being applied to the right tasks.
The following 5 tools offer solutions for project management, workflow support, and team collaboration concerns:
Wake offers a solution to a problem designers often face; how to share information and collaborate among team members without interrupting a project’s workflow.
With Wake, you can upload and share sketches, screenshots, or other information, without ever interrupting your Photoshop, Sketch, or Illustrator design flow.
For example, you can use Wake’s iPhone app to capture notebook or whiteboard content and instantly share it with your team. The app allows you to share and see project feedback on the go.
This ability to share information without interrupting workflow makes the entire design process more transparent for your entire team, even those outside of design. With Wake, information can be shared publicly, so everyone knows what everyone is working on; or shared privately with selected individuals or stakeholders.
InVision is an excellent choice if you need a tool that integrates prototyping, workflow management, and collaboration functionality into a single platform. With InVision, you can avoid the need to select a variety of tools to perform a variety of tasks. Whether you are a team leader or a freelancer, this design-driven project management tool will manage your prototyping, design sharing, collaboration and modification, and user test activities from a central location.
InVision makes prototyping easy. Simply upload a static design file, add animations, transformations, and gestures, and you can create an interactive, high-fidelity prototype in about 5 minutes.
InVision has been used by approximately 2 million designers, including freelancers, design agencies, and design teams working for major corporations. If you request a free trial, you’ll be allowed to work with a single prototype for as long as you wish while you learn more about this tool’s functions and features.
Using separate tools for task management, time tracking, and invoicing sometimes makes sense, but it’s almost always better to do it all using a single platform, like Active Collab. Active Collab provides a one-stop solution for all your team’s business needs.
Features include project tracking, advanced to-do lists to keep things organized, team collaboration, time tracking, and invoicing. Active Collab runs on the cloud so no setup is required on your part – you’ll be up and running within 2 minutes. Also, you have the option to self-host the app on your own server for a one-time fee.
More than 200,000 designers and project managers currently use Active Collab on a regular basis. Its 30-day free trial should give you plenty of time to test it and see if it’s the right fit for you.
Paymo is well suited for teams working for small and medium-size businesses who are looking for a tool that makes project management easy. Paymo’s progressvisual Kanban boards allows you to create your workflows and move the associated tasks through sequential and logical steps. Tasks can easily be changed or added, you can organize tasks into lists and, using drag and drop, simply reorder them when necessary.
Paymo’s features include a real-time collaboration capability, project templates designed to save you time, Gantt charts, and a dashboard to provide instant project overviews. A 15-day unlimited free trial is yours for the asking.
Pinnery is the perfect project planning tool. Place your ideas on Pinnery’s color-coded board, move the ones you wish to pursue to the to do list, attach files and pictures to each item on your list, check what is in progress and what has been accomplished, and before you know it, your project is done.
Pinnery keeps everything organized, everything can be shared with everyone, and a perfect overview of project status is always available. This app also encourages team collaboration, no installation is required on your part, and you can get started for free.
Ending Thoughts
No matter what your workflow or project management issues may be, you’ll find the right solution here. Depending on the tool or tools you select, your workflow and task management, collaboration, or project planning needs will be in good hands. And you can devote more time to design issues or other pressing issues.
Several of these tools feature mobile apps than allow you to check status or coordinate with your team or project stakeholders while on the go. Freelancers can benefit from several of these tools, while others are best suited for use by teams and team leaders.
A good stock image is like a good design: you want it to be powerful, persuasive, and memorable; without drawing attention to itself. It can seem like a difficult balance to achieve, but a little effort on your part will reap rewards.
Stock images are used for a variety of reasons. Most commonly, they’re great if you simply do not have the time, budget or resource to conduct your own photography shoot. Stock images are also great placeholders for designers when pitching to a client—you can experiment with ideas and deliver mockups that reflect the final design, without the full cost of original photography, knowing that you intend to swap out the images later.
Sometimes, professional photographers post stunning images, of unique moments, that simply cannot be recaptured, no matter how high your budget. But almost everyone on the planet has access to a camera, and with 3 billion budding photographers out there, not all stock photography is equal.
Here’s some insider knowledge on how to distinguish quality images from low-quality stock.
1) You get what you pay for
It may be a cliché, but it happens to be true: quality products cost money. A quality photograph is normally taken by a skilled photographer who has spent years, if not decades honing his or her craft. Many professional photographers spent years in college learning about lighting levels, composition, and a host of other technical details that combine to produce a great photograph. Most professional photographers use expensive equipment. The photographer might have invested heavily in a shoot, paying a model, travelling to a location, or hiring a studio. All that investment has to be paid for.
To give away a photograph for free, you need to be cutting corners somewhere. That’s not to say that there are no quality stock images available for free, but there are fewer. Purchasing from a reputable supplier such as iStock by Getty Images means you’re guaranteed all the quality of a professional shoot.
2) Avoid filters
A good photograph is just that. It doesn’t anticipate a design, or a style. We see thousands of images submitted to stock sites that have filters applied, and this raises two concerns: firstly, filters are often applied to disguise flaws in a photograph that may become apparent once it’s introduced to your design; secondly filters always add a flavor to a design that you may not have intended.
If you want to use a filtered image, first select a great photograph, then apply the filter yourself in an application like Photoshop. Not only will you be confident that the image isn’t hiding a flaw, but you’ll retain control of the look and feel of your design.
3) Look for processed images
At the other end of the scale from filters, is professional processing.
Professional photographers shoot images in raw format, rather than jpg, because it stores more data and thus enables the resulting image to be processed more easily. Photography is more than just pointing and shooting, processing is an essential part of a professional photographer’s workflow.
Images that have been processed have deeper blacks, more detail in the highlights, greater contrast, and more vibrant colors. This richness of detail produces an image that pops off the screen. Free stock rarely demonstrates this level of quality, due to the time that the photographer needs to invest.
4) Avoid flat
Flat design may be all the rage in web design, but flat images hold less visual interest. An experienced photographer will capture not just what’s in front of the lens, but the spirit of the subject as well.
Take for example, an image of a building: an amateur photographer might frame the shot full frontal, in order to capture as much of the building’s facade as possible; an experienced professional will instead pick out an architectural detail, shot at a dynamic angle, making use of perspective, to record not just the facade, but the presence of the building. It’s a skill that takes thousands of shots to perfect.
5) Avoid xeroxing
The biggest asset any creative brings to the table is their ideas, and photography is no exception. A good photograph conveys an idea, an emotion, an event, in a way that is unique to that photographer. Free stock tends to be produced as stock. As a result, rather than taking an original approach to an idea, the photographer mimics other stock images.
For example, while a professional photographer might document a business meeting, a free stock image will show the infamous handshake shot that has been duplicated thousands of times—this is how we end up with so many clichéd stock images.
If it looks like a stock image to you, it will look like a stock image to everyone else—even if they don’t know what stock is.
Premium stock vs. free stock
Is there any such thing as high-quality free stock? Of course! Many of the world’s best photographers give away some, or even all of their images. Even professional photographers who sell premium stock will often give away lesser images for free, or with a restricted license.
The problem with free stock is that it so often looks like stock, and therefore the project/brand/user of the image fails to stand out and make an impact, as so many others are using the same image.
When you purchase premium stock you know you’re buying an image that doesn’t look like stock—and doesn’t convey the negative associations that free stock carries with it. Premium stock raises the perceived quality of your design, both for your client, and your client’s customers.
iStock by Getty Images believes that no one should have to settle for ordinary images. With over 8 million exclusive images, iStock are the leading stock provider of images, illustrations, graphics and video. High quality, at low prices.
So you can try out iStock by Getty Images for yourself, they have kindly provided WebdesignerDepot readers with a 20% discount for new customers, just enter code ‘NEWWDD20′ at the checkout. (Code valid 22nd–29th November 2016.)
[– This is an advertorial on behalf of Getty Images –]
CSS blend modes and filters allow for effects that were not possible before. When applying these new options to images, you can create even more impressive effects by stacking or repeating multiple attributes in clever ways. And all of this is done in a nondestructive way.
Bennett Feely and his Code Snippets
Bennett Feely from Pittsburgh, Pennsylvania and his project Image-Effects on Github provide a great example for effects that can be achieved with an intelligent use of combinations or repetitions of different modern CSS attributes, for which you would not have used pure CSS until now.
Bennett has built twenty effects. All of them are displayed while applied to the same original image, as well as with the according required code snippet in CSS and SCSS. You can either copy the snippets directly from the demo page, or switch to Codepen, where you get to play around with the settings, and a live preview.
Bennett also provides all effects as a CSS library, which is easy to integrate into your projects, and only weights 1300 bytes when compressed. Of course, working with the uncompressed version of 12,8 kilobytes is more comfortable 😉
In general, it is possible to use the effects right away. However, Bennett rightly recommends touching upon certain parameters, depending on the image you want to display.
Bennett’s Image-Effects use @supports for feature detection. When it’s detected that a browser is unable to display the set attributes and values, the image is depicted without the effects. We can definitely be okay with this type of fallback.
The Application is This Easy
The individual effects are defined as classes, which you apply to your images accordingly. The easiest way to do this is to label a Div container with the respective class and place your image inside.
To avoid odd initial effects, you should assign the correct values for width and height to your image. This way, you make sure that the browser will use the correct image size as a placeholder right away.
Black Friday is always a busy day in the eCommerce world. Although much of the focus tends to be on household items and consumer electronics, web designers have not been left out of the picture.
This selection of design tools, aids, UI kits, etc., features something for just about everyone. The savings are significant. And if you’ve been thinking of purchasing any of the items listed below, there won’t be a better time than now.
In the brick and mortar world, the driving force behind Black Fridays is to get people into a buying mode and get them in the store. The eCommerce world may not be all that different. But for the Black Friday specials featured here, quality is the rule and not the exception.
ThemeFuse is a source of more than 30 high-quality WordPress themes for those designers and developers who want to create original websites for their clients, and do so quickly and easily.
On Black Friday only, one or more of these WP themes can be yours at a 40% discount.
These themes run the gamut from automotive, business, and religion, to travel, blogs, e-commerce and everything in between.
The Core for example, which is a massive multi-purpose WordPress theme, comes with more than 20 demo themes included and has everything you’d ever need in a website;
You can try any WP theme before purchase. Simply create a test lab account, log in to WordPress, and test drive the theme of your choice. You’ll quickly discover that ThemeFuse’ themes, with their original and creative designs, are easy to use, thanks in part to the visual page builder.
Dreamstime, with the stock photo industry’s largest client database, is an excellent resource for quality stock images.
Dreamstime is offering a 50% discount on all and any subscriptions from Black Friday through Cyber Monday. This gives you plenty of time to drill down to find many great images that you might have otherwise passed up for budgetary reasons.
Dreamstime is a media provider to 95% of the Fortune 500 companies, which says much about the quality you can expect; not only in Dreamstime’s stock photo selection, but also in their HD and 4K footage collection.
Thousands of fresh files are added every day, so although you’ll never catch up, by setting aside a short time during the holiday break, you can come up with some real bargains
Black Friday through December 2 is your opportunity to purchase an annual subscription to Proto.io at a 30% discount. The promo code is BLACKFRIDAY2016. This discount is available to new customers and to existing customers wishing to upgrade from a monthly to an annual plan.
Proto.io is an industry-leading prototyping platform that gives its users the power to create web and mobile prototypes that are not only pixel-perfect, but have the look and feel of the real thing. Designers, entrepreneurs, freelancers, and developers work with Proto.io to cover the entire design process, from wireframes and mockups, to user testing of interactive, high-fidelity prototypes.
Proto.io is easy to use, and no coding or special technical skills are required. This is an excellent chance to purchase a premium prototyping platform at a bargain, Black Friday price.
Begin with a free trial and then upgrade until December 2 to get their special Black Friday deal.
Webflow, a premier all-in-one web design platform, is offering its website templates for 50% off as their Black Friday special. Simply enter BLACKFRIDAY at the checkout. You’ll find more than 100 business, portfolio, and blog templates to choose from. Every Webflow template is fully responsive.
You can customize any element of a template’s design to suit your needs, and you can do so without the need to write a single line of code. Each of these templates is built with Webflow’s 100% visual responsive web design tools, using standards-compliant HTML5/CSS3 and JavaScript.
Themify is celebrating Black Friday through Cyber Monday with never-before-seen discounts, plus 10 Master Club giveaways. Promo code BLACKFRIDAY will get you a huge 50% discount on all Club Memberships, plugins, and WordPress themes.
The 50% discount does not apply to the Lifetime Master Club membership, but Themify is offering a $150 discount to join (use promo code BLACKFRIDAYLIFE). With the discount, you can get lifetime access to products, support, and updates for only $249! Topping things off, you can enter the Master Club giveaway promotion from Black Friday through Cyber Monday for a chance and winning a free membership.
Visual Hierarchy has always been dedicated to selling premium design products at affordable prices. On Black Friday, you can take your pick of VH’s top-selling products, and all other items, for up to 60% off. Since Visual Hierarchy is a marketplace where designers can sell products as well as purchase them, you’ll find many useful and creative items you won’t find elsewhere.
If you’re in the market for Icons, Fonts. Mockups, UI Kits, and more, this is your chance to lock in some real Black Friday bargains.
Wrapping it up
There are Black Friday bargains here for those already using the products being promoted as well as for new customers. Designers will enjoy the specials offered on Dreamstime’s stock photos, which are always in demand. The same is true for the Visual Hierarchy promotion. Their quality products, plus many innovative products being sold by designers, are always available.
When you can buy a product you need for your work, for anywhere from 30% to 60% off, it’s always a good deal. Proto.io offers an industry- leading prototyping platform. Themefuse and Themify are known for their high-quality themes and Webflow for its premier web design platform. If they are new to you, both are well worth a look, but the same can be said for every Black Friday promotion in this list.
The following is a post by Levi Gable. Levi digs into the idea of separating the CMS from the presentation of content within that CMS. As Levi will explain, there is a freedom there that can feel mighty good to a web developer. A website can digest an API and present content in whatever the hot new way to do that is. But even more importantly, an API can serve multiple publishing platforms. Levi demonstrates this as well, by having this one API fuel not just a templated website, but a React Native mobile app, and even an Apple Watch app.
There is a trend in the web development world toward the API-based CMS architecture. Also known as “decoupled” or “headless”, it allows developers to separate the content management from the frontend implementation and connect to the CMS via an API. This is an exciting approach to website and app development, offering more freedom and flexibility. I want to show you my process for setting up and connecting to an API-based CMS.
For each type of content you need for your site, you develop in three steps:
Create the custom content type and configure its fields
Set up your app to retrieve that content from the API
Load the content into your page template
Let’s take a look at each of these steps in a little more detail as I walk through how to set up a simple news article website (demo website) with a homepage and article pages.
1) Article Pages
Create the Article custom content type
When developing a custom content type, you need to determine all the content fields you need. For example, a blog post might be a combination of text, images, and blockquotes. For a product, you would need to define the image fields, number fields, and text fields specific to your product page design.
For our article pages, we need to have a UID (unique id for SEO-friendly urls), publish date, title, main image, author, and three different repeatable sections that can be mixed and matched: text, quotes, and images.
The process for actually building the custom type varies from one CMS to another, but we’ll end up with a custom type that has all the fields we need to fill in with content. Here’s what our article custom type looks like:
The CMS I am using for this example is prismic.io, although any CMS that outputs JSON could be adapted for use here. For example, CSS-Tricks has a number of articles about the WordPress JSON API and it appears Perch Runway 3 will have “headless CMS” capabilities. Prismic also uses JSON to construct your custom types and configure your content fields. I have included the JSON code I used for my custom types for this project in the project package on GitHub. You can find them in the `customTypes` folder.
Once you’ve created and configured your article custom type, you will create a few articles, and next we’ll see how to query the API to retrieve them.
Set up the front-end app to query the API and load the articles
This is where an API-based CMS really shines. You can build your site however you want, using whatever technology you prefer. Many of the API-based CMSs out there provide specific development kits for the major technologies, which provide all the methods needed to query the API and parse the returned data. This makes it easy to bootstrap your project.
No matter what you code with, you will need to query the API to retrieve the content you want to display. I built this example site using prismic.io’s NodeJS development kit. I chose NodeJS because it is a simple and easy JavaScript server-side platform.
Let’s setup our app to load the pages via their UIDs. Here’s an example of the code we can use to query the API for our content pages.
app.route('/:uid').get(function(req, res) {
var uid = req.params.uid;
api(req, res).then(function(api) {
// Here we are querying for a custom type ‘article' by its unique ID
return api.getByUID('article', uid);
}).then(function(pageContent) {
res.render('article', {
pageContent: pageContent
});
});
});
Load the content into the page templates
Once we’ve collected the content we need from the API, then all that is left is to load the content in our templates. Our query to the API will return a JSON object which contains all of our content.
The development kits will also come with helper functions to make it easy and simple to load the content into our templates.
This example website uses the Pug (previously Jade) templating system to create the html for the pages. Integrating the page content is quick and easy. All we need to do is replace our static content with the content queried from the API.
Below I include the code to integrate the content into the template, but don’t include sections like, the header or the layout files. If you want to view these, feel free to check out the full project on GitHub.
extends ./layout.pug
block body
include ./partials/header.pug
div.article.container
include ./partials/back.pug
h1
//- Here we insert the StructuredText field ‘title' from the custom type ‘article'
!= pageContent.getStructuredText('article.title').asText() || 'Untitled'
img.article-image(src=pageContent.getImage('article.image').url, class='star')
- var sliceZone = pageContent.getSliceZone('article.body') || {}
for slice in sliceZone.slices
//- Render the right markup for a given slice type.
case slice.sliceType
// Text Section
when 'text'
div.article-section.text
!= slice.value.asHtml()
// Quote Section
when 'quote'
div.article-section.quote
span.block-quotation !{slice.value.asText()}
// Image Section
when 'image-with-caption'
- var imageWithCaption = slice.value.toArray()[0]
- var imageUrl = imageWithCaption.getImage('illustration') ? imageWithCaption.getImage('illustration').url : ''
- var caption = imageWithCaption.get('caption')
div.article-section.image
img(src=imageUrl)
if caption
p
span.image-label !{caption.asText()}
include ./partials/back.pug
We are now successfully displaying the pages for our website! We will quickly go through this same process to set up our homepage.
2) Homepage & Layout
Create the layout custom content type
We will need a custom type for the layout of the site. This will include text for the logo, the link to this article, and the text for that link. The homepage itself will be composed of the content from all the articles, so we don’t need to create a custom type for it.
Query the API and load the homepage
To get all the content we need for the homepage, we will actually query the API twice. Once to get the layout content, then another time to display all of the articles in tiles on the homepage. Here is what this might look like using NodeJS:
// Route for homepage
app.route('/').get(function(req, res) {
api(req, res).then(function(api) {
// Query the site-layout content
api.getSingle("site-layout").then(function(layout) {
// Then query all the articles and sort by date
api.query(
prismic.Predicates.at("document.type", "article"),
{ orderings: '[my.article.date desc]' }
).then(function(articles) {
res.render('homepage', {
layout: layout,
articles: articles.results
});
}).catch(function(err) {
handleError(err, req, res);
});
}).catch(function(err) {
handleError(err, req, res);
});
});
});
Load the content into the homepage template
Then it’s a simple matter of loading the layout and the article content into the homepage template. To add the layout content, just need to update the header.pug file.
On the homepage, we will feature the most recent article at the top. So we take the first article and load it into this template:
div.featured-article-container
div.featured-article(style="background-image: url(" + article.getImageView("article.image", "featured").url + ");")
div.featured-content
h2
!= article.getStructuredText('article.title').asText() || 'Untitled'
//- display first valid slice text and limit it respecting the end of words.
- var firstParagraph = article.getFirstParagraph()
- var firstParagraphInPost = firstParagraph ? firstParagraph.text : ''
- var textLimit = 100
- var limitedText = firstParagraphInPost.substr(0, textLimit)
p.description
if firstParagraphInPost.length > textLimit
= limitedText.substr(0, limitedText.lastIndexOf(' ')) + '...'
else
= firstParagraphInPost
a.button.featured-button(href=ctx.linkResolver(article)) Read the article
Then all you need to do is integrate the rest of the articles.
div.article-tile
div.article-tile-image(style="background-image: url(" + article.getImageView('article.image', 'tile').url + ");")
img.article-tile-mobile-image(src=article.getImageView('article.image', 'tile-mobile').url)
div.article-tile-content
h2
!= article.getStructuredText('article.title').asText() || 'Untitled'
p.meta-info
!= article.getText('article.author')
span.date -
!= ctx.dateConverter(article.getTimestamp('article.date'))
//- display first valid slice text and limit it respecting the end of words.
- var firstParagraph = article.getFirstParagraph()
- var firstParagraphInPost = firstParagraph ? firstParagraph.text : ''
- var textLimit = 300
- var limitedText = firstParagraphInPost.substr(0, textLimit)
p.description
if firstParagraphInPost.length > textLimit
= limitedText.substr(0, limitedText.lastIndexOf(' ')) + '...'
else
= firstParagraphInPost
a.button(href=ctx.linkResolver(article)) Read the article
Once the integration is complete, we have our website pulling and displaying content from the API!
3) Other uses
Another benefit of using API-based CMS is that you can query and load content in other formats, like phone apps. To demonstrate this, I also created an iOS app that queries this same API and displays the news articles on your smartphone.
I built the app using React Native and followed the same process as above. I chose React Native because it allows you to create rich mobile UI using only JavaScript. While I only built an iOS app, React Native also makes it easy to also run your app on Android as well.
With the custom types already in place, you can start by querying the API. I provide some sample code below, but feel free to explore the entire project here in my GitHub repository. Here is the query to get the content for an article.
// The query for the article
async function article (uid) {
try {
const api = await PrismicHelper.getApi()
const layoutDoc = await api.getSingle('site-layout')
const articleDoc = await api.getByUID("article", uid)
return {layoutDoc, articleDoc}
} catch(error) {
console.log(error);
return {};
}
}
Once you have queried the content, you can display it in your views using the same methods that we used above for our NodeJS website. Again, here is a sample of what it looks like.
The benefit of creating a phone app separate from the website is that you can better connect with your audience and make it easier for them to have access to your content via their phones. You can even take it to the next level and send out push notifications every time you release a new article and truly keep your audience up-to-date. I found it very easy to integrate notifications using Urban Airship.
I hope that this article gives a good idea of what to expect with the API-based CMS approach. I love the freedom and the level of control that the API-based CMS provides. Starting with setting up your content types for exactly what you need. Then being able to use the technology and templating system that works best for you and your project. And finally connecting to the API to easily integrate your content into your templates.
It’s a perfectly reasonable to want to style the marker of list items. You know: blue bullets with black text in an unordered list. Or red counters with knockout white numbers in an ordered list.
There is a working draft spec that defines a ::marker pseudo-element that would give us this control.
/* Not supported anywhere; subject to change */
li::marker {
color: blue;
}
It’s possible to do this styling now, though, thanks to CSS counters. The trick is to remove the list-style, then apply the markers through pseudo-element counters.