Patient dashboard

How to Develop a Telemedicine App?

Today, you can get anything on demand, from taxis to food, personal tutors and even doctors. While the first three services have been popular for some time, on-demand doctor consultations came into the picture not so long ago. Telemedicine app development has drawn lots of interest from doctors, hospitals, clinics and patients.

According to a report by MarketWatch, the US telemedicine market saw revenue of around $11.8 billion. 50% of the hospitals in the US use telemedicine programs, but it has now also become interesting for private medical practices, healthcare systems, entrepreneurs, healthcare systems, and insurance companies.

A survey by Mordor Intelligence says that global IT healthcare is expected to reach $20 billion by 2020. Telemedicine accounts for one-quarter of this market. What is the reason that the telemedicine app development has experienced such significant inflation? In this article, we shall discuss what is telemedicine, reasons why telemedicine app development is gaining a lot of traction, how to develop a telemedicine app and how emerging technologies can be implemented in telemedicine.

What Is Telehealth and Why Is IT Gaining Traction?

Telehealth application brings healthcare providers and patients closer in a digital environment and enhances access to care. It helps patients to interact with physicians from anywhere and anytime. In contrast, physicians can assess, diagnose, and treat patients for a wide range of appointment types, including follow-up routines and consultations.

Three minutes is the average time a patient waits to connect with a doctor using a telehealth application. Therefore, patients don’t need to sit in waiting rooms for hours to get a consultation from the doctor.

Telehealth Apps can be of different types, including:

  • Real-time Interaction
    Healthcare providers and patients can interact in real-time with the help of video conferencing. The telehealth app for real-time interactions allows both patients and doctors to see and hear each other.
  • Remote Monitoring
    Telehealth applications can also be used for the management of patients at high risk and allow healthcare professionals to monitor the patient’s activities and signs remotely via wearable devices and IoT-enabled health sensors.
  • Store-and-forward
    Store-and-forward telemedicine apps allow healthcare providers to share patient’s medical information, including blood tests, lab reports, videos and imaging studies with a radiologist, physician or any other specialist.

Why Is Telemedicine App Development Gaining a lot of Traction?

  • Convenience
    Booking appointments in advance, driving to a hospital and waiting in a long queue is not a convenient approach to get assistance from doctors. A study by Cisco says that 74% of patients prefer access to telehealth services over in-person interactions with healthcare providers.

    Using a telemedicine app, patients don’t need to wait in long queues to visit different specialists. Instead, they can schedule a remote appointment with a doctor and connect at the earliest convenience. It helps in starting the necessary treatment quickly and effectively.

  • Medical Record Keeping
    Telemedicine apps make it possible for doctors and patients to view patients’ medical records quickly. It overcomes the interoperability problem by allowing various doctors to get access to the patient’s previous records quickly. As a result, doctors can treat patients in a much better way by looking at their historical medical records.

    Also, patients can share their medical records with family members, friends and doctors. They no more need to keep paper-based medical files or reports in their lockers or drawers.

  • Time Management of Healthcare Specialists
    With telemedicine app, healthcare providers can organize their tasks more effectively. Since doctors can treat patients and provide consultation from the comfort of their home or office, they will be able to consult more patients at once. Telemedicine software solutions can provide a better life-work balance to doctors.
  • Unified Patient Monitoring and Management System
    Telemedicine apps can help patients with updates to prescriptions, follow up consultations, chronic disease monitoring and more.

How to Develop a Telemedicine App?

If you are thinking about telemedicine app development, you first need to identify users of the application.

There can be following users within the telemedicine app platform:

  • Patients
    Patients are users with necessary permissions who can request online consultation with a doctor.
  • Doctors
    Doctors are users who provide online consultation to patients, view patients’ profiles, lab reports and schedule appointments.
  • Lab Technicians
    Lab Technicians are users who share lab reports with doctors and patients and view and process lab test requests.
  • Admin
    Admins are users with administrative responsibilities and security levels.

Here’s How a Patient Dashboard Would Look

Patient dashboard

If you log in as a patient in the telemedicine app, you can find the following components in your app:

  1. Profile
    Patients can create profiles by entering their essential information, including name, email address, phone number, age, gender, medical history, problems they are suffering from and other information that is required to start treatment. They can update their profile information anytime.
  2. Find a Doctor
    This feature would allow patients to find doctors using filters, including specialty, gender, language and insurance provider. It would help patients to find a physician that meets their situation and needs.
  3. Appointment Scheduling
    Patients can browse doctors’ profiles on the telemedicine app and book an appointment with a doctor by looking at their availability via the calendar.
  4. Real-time Visits
    Patients can interact with doctors via video and audio calling. Video conferencing should be smooth and high-quality so doctors can examine patients remotely to recognize signs and symptoms of diseases.
  5. Payments and billing
    Patients can pay online for their visits. Telemedicine apps should be able to provide multiple payment options so that users can choose the convenient method.
  6. Messages/Instant Chat
    Patients can also send messages to the doctors related to their problems or chat with them instantly.
  7. Previous Medical Records
    Patients and doctors can access their past medical records from the telemedicine application. It helps patients consult new medical providers quickly and effectively as they can have access to patients’ medical records quickly.
  8. Notifications
    Remind patients about upcoming visits a few minutes before the scheduled time. Also, notify patients when the appointments are approved or rejected.
  9. Book lab test
    Patients can book lab tests advised by the doctor through the telemedicine app.

Doctor’s Dashboard

Let’s discuss the main features of a telemedicine app for healthcare providers/doctors:

  1. Doctor Profile
    Doctors should be able to create profiles so patients can check their backgrounds, certifications and hospital affiliation.
  2. Appointment Schedule Management
    Doctors should be able to make changes to their schedules and manage their day-to-day availability. They should be able to accept and reject appointments.
  3. View EMRs
    Telemedicine apps can be integrated with EMR systems so that doctors can view patients’ medical records and lab reports in real-time.
  4. Provide Digital Prescriptions
    The telemedicine app can enable doctors to prescribe treatment and medicine right in the app. Patients can buy medicines using prescriptions provided by doctors or get other health services like lab tests through the app.
  5. Messages
    With the Messages feature, doctors can chat with patients in real-time using instant messaging. Doctors can respond to the patients’ queries and prescribe them medicines and treatment through messages.
  6. Calls
    With Calls feature, doctors can connect with patients through face-to-face video consultations. It helps doctors not only in diagnosing patients’ symptoms but also in providing effective treatment.  
  7. Visit Patients’ Medical History
    The option of viewing the patients’ medical history allows doctors to visit patients’ medical history within the telemedicine app. The patient history tab shows all patient visits along with the doctor’s name, visit date and type of treatment provided by physicians. It helps doctors give effective treatment to their patients.
  8. Video Session Recording
    Doctors can record audio and video consultations to control the quality of their service. It can help protect both doctors and patients in case of any dispute.
  9. Notifications
    Alert doctors about their appointment a few minutes before it gets started. Also, notify doctors when a patient requests for an appointment so that they can quickly accept or reject it based on their availability.

Lab Technicians’ Dashboard

Lab Technicians can have the following features within their telemedicine app:

  1. Lab Technician’s Profile
    Lab Technicians should be able to create their profile by providing necessary information, including certifications, license, and background details.
  2. View Requests 
    Lab technicians can view the requests received from patients and add them to the calendar.
  3. Assign tasks to lab professional
    Based on test requests received from the patients, lab technicians can assign tasks to lab professionals to pick test samples from the patients.
  4. Share reports with doctors and patients
    Lab technicians can share lab reports from telemedicine app with doctors and patients.

Admin’s Dashboard

By logging in as the admin, you should be able to see the following navigation:

  • Users
    Admin can manage all users of the telemedicine app. They cannot only manage the users, but they can also remove or edit existing information of users.
    Admins have the right to approve the profiles of doctors and lab technicians based on their certifications or licenses.
  • Documentation
    Admins can access all documents related to medical records, patient care, lab test reports, and insurance documents. Accessing documents can help admins take evidence-based decisions, create patient registry functions, provide evidence for legal records, and research large patient populations efficiently.
  • Reports
    Using AI, data collected from the telemedicine app can be converted into valuable insights in the form of reports. Admins can access this report and make critical decisions related to the enhancement of the application.
  • Finances  
    Finances feature provides admins an opportunity to manage the money flow efficiently, for example, automatic payment reminders and online invoicing within the telemedicine app. This feature allows admins to not only track expenses and income, but also generate and send online invoices, make data-driven business decisions, and accept online payments.

Key Features of the Telehealth App

Below are the key features of the telemedicine app you need to consider before initiating the telemedicine app development:

  • Encryption and Security Protocols
    Using security and encryption protocols, a telemedicine app can allow patients and doctors to keep confidential patients’ data secure and safe. 
  • Video Conferencing
    Video conferencing allows doctors and patients to interact face-to-face on the mobile device and computer with high-quality audio and video. 
  • Instant messaging
    With instant messaging, patients can exchange text messages with doctors in real-time during or after the appointment if they need any clarifications. 
  • Appointment Management
    Appointment Management allows patients to select an available slot from the doctor’s calendar and schedule appointments themselves. 
  • Clinical Documentation
    Clinical Documentation facilitates doctors to provide patient care while considering the privacy of patients’ records. 
  • HIPAA Compliance
    When HIPAA compliance is integrated into the telemedicine app, it can help reduce errors through secure electronic communication of healthcare transactions. 

How Can Emerging Technologies Impact Telemedicine App Development?

1. Artificial Intelligence

AI and Telemedicine combined can diagnose illnesses more accurately and reduce costs. AI is transforming healthcare in a variety of ways. In a survey of 56 renowned healthcare organizations, TCS revealed that 86% of them are already using AI and are planning to spend around $54 million on it by 2020. For example, doctors have already adopted a Google Machine Learning Algorithm to treat diabetic retinopathy and diagnose remotely. 

We have explained how AI can help transform telemedicine app development below:

  • Treatment Recommendation
    IBM Watson recommends treatment plans to cancer patients with machine learning at a hospital having 327 beds in Jupiter, Florida. Using ML, IBM Watson provides clinical data corrected and reviewed by physicians.


    Implementing machine learning algorithms like IBM Watson in telemedicine applications can drive better diagnoses with less human intervention. For example, an algorithm should monitor every treatment for some disease and then ask patients how long it took them to feel better on average. The telemedicine platform can then help doctors recommend treatments based on previous success rates. 

  • Assisting with eldercare
    According to research by Gartner, telehealth will come in the form of robots at some point and will help deliver home healthcare. As the demand for home healthcare workers continues to exceed supply, smart machine robots are growing in utility.One of the examples of home telehealth technology is eldercare-assistive robots, which are smart machines and move semi-autonomously, use sensors to understand environments and carry out required tasks.


    The Japanese government has provided funding to develop robots to help older people in walking, bathing, monitoring, and waste disposal. A robot named “IBA” uses smart rubber sensors to find the weight of an elderly person without lifting. 

  • Making better diagnoses
    Doctors can monitor, diagnose, and treat patients remotely using a telemedicine app. When remote monitoring gets combined with machine learning, telemedicine apps can provide better diagnoses with less specialty staff.A startup named “FDNA” is looking to use the machine learning algorithm for detecting rare genetic diseases from pictures of patients’ faces. Currently, patients with rare genetic disorders have to visit seven doctors on average, before identifying what they have. Sending photos of faces to the machine learning algorithm via a telemedicine app can decrease that number to zero.  

2. IoT

IoT can enhance telemedicine app development in many ways. It can help in providing a quality of care that’s much better than in-person treatment techniques. 

  • Allowing doctors to get data from medical devices
    One of the obstacles of telemedicine app is that although physicians can find a rash on patients’ skin or notice that they have sweaty or pale skin via video conferencing, they cannot take patients’ blood pressure (BP) or listen to their heartbeat. Doctors usually ask patients to measure their blood pressure or pulse rates if they have BP cuffs at home. 

    A company named “CyberMed” wants to combine telemedicine and IoT and allow people to use medical devices for the produced for the company’s patients. People can buy pulse oximeters or digital stethoscopes and use them for telemedicine appointments. Data collected by devices gets transmitted to the cloud for evaluation by the doctor. 

  • Remote Monitoring
    People living in rural areas often get suffered because of the lack of appropriate health monitoring. It can be possible with the help of small yet powerful wireless sensors connected through IoT to monitor patients in such areas. 

    Smart sensors can collect the patient’s data securely, analyze the data using complex algorithms, and share the collected information with the concerned health professionals.


Telemedicine App Development requires a lot of attention to detail. Apart from identifying the features to be included within the app and technologies to be used, you need to consider that the app complies with the legislation in your targeted country or regions. You need to add detailed information on each doctor and allow patients to rate and review doctors to make the telemedicine app credible for your users.

Source link

Pointing to host db

Docker Commands to Containerize an Application

Docker is an exciting technology when the developers are focusing on the design of their applications in a cloud-native approach. One of the key characteristics of designing a cloud-native application is to containerize the application. Designing applications such way will save you from hearing some of the words from other developers during development time.

  • “The application is not working in my local machine!”
  • “I’m facing version conflicts.”
  • “Libraries are missing.”

Every time we onboard new developers in our team we have to fix several issues to build and run the applications successfully in a new machine that leads the onboarding period a bit longer and forces another expert to engage when he/she is focusing on something deliverables. 

Hence, the realization is let’s containerize the applications that I am working on. Throughout this tutorial, will share with you the commands that I used to make it happen finally. 

What Is a Docker Image?

Docker image is nothing but a snapshot of the current state of your application which is running in your local. Image is used by Docker engine to run the application exactly as same as it is running in your machine without any further actions.  The same image can be used for shipping applications and run in all the deployment environments which means you don’t need to worry about the environment or dependencies to keep running the application in production. 

Create an Image

List down all the instructions in a text file and name it as Dockerfile. 

Navigate to the terminal to the same directory of Dockerfile

docker build -t userservice .

List the View of Created Images

docker images 

docker images -a Show all images (default hides intermediate images)

Delete Image

docker image rm userservice 

docker image rm $(docker images  -aq)  Delete all images by id 

What is a Docker Container? 

Docker containers are isolated Linux environments created by the Docker Engine where the applications are running in a container besides other containers. 

Create a Container

 docker run --rm -it --name userservice --publish 8081:8080 userservice

  •  --rm  option is to delete the container when it shutdown. 
  •  --name flag  go give the container a name
  •  --publish  is to bind the host port 8081 with the container port 8080

List View of The Created Containers

 docker ps 

 docker ps -a 

Inspect low-level information of the container: 

 docker inspect userservice 

View the logs of a container

 docker logs userservice 

 docker logs -f userservice 

(-f is to follow log output(

Persist Application Logs Into the Host Directory

Create a directory where you want to save the application log files then mount the volume with Docker by appending  --mount  flag in  docker run  command. docker run --rm -it --name userservice -v $HOME/docker/logs/userservice:/var/log --publish 8081:8080 userservice 

Persistent Database

By default, Docker containers are transient which means you will lose the data once the containers are deleted. To save the data for future use you need to persist database state in the host directory. 

 docker run -d --name postgres --publish 5433:5432 -e POSTGRES_DB=local_userservice -e POSTGRES_USER=local_userservice -e POSTGRES_PASSWORD=userservice_pass --hostname postgres -v ${HOME}/docker/postgres-volume:/var/lib/postgresql/data mdillon/postgis

Separate Container Configuration Data

Environment variable:

docker run -d --name postgres --publish 5433:5432 -e POSTGRES_DB=local_userservice -e POSTGRES_USER=local_userservice -e POSTGRES_PASSWORD=userservice_pass --hostname postgres mdillon/postgis

Find the Log Files of docker-engine

Docker log directory


Run the container in an interactive mode that will populate the console log. Flag  -it  in container run command is to run the container in interactive and pseudo TTL mode. 

Attach the Container to A Network

View the all available networks

 docker network ls 

Let’s attach a running container postgres to the projects_default network.

 docker network connect projects_default postgres  

Inspect the projects_default network to see the connected containers.

 docker inspect network projects_default  

Hide the Secrets from Container

Don’t compromise the database password or AWS keys with the container. There are a couple of ways to keep aside the secrets from the container, environment variables, mount a directory and put the secrets in a file, and use any of available the secret service, IAM role of AWS. 

Mount directory, where is the file and want to make it available it userservice/config directory inside the container. 

 mkdir -p /Users/amjad.hossain/docker/userservice/config  

 docker run --rm -it --name userservice --mount type=bind,source=/Users/amjad.hossain/docker/userservice/config,target=/usr/src/userservice/config --publish 8081:8080 userservice

SSH into Containers

 docker exec -it userservice /bin/sh  

 docker exec -it postgres bash  

Stop container

  docker stop postgres  

Delete container

If you use  --rm to run a container that will remove the container when you stop it.

Delete a stoped container:

 $docker rm postges 

Forcefully delete a running container:

 $docker rm -f postges 

Delete all containers by id:

 docker rm -f $(docker ps -aq)  

Point Application Container to Host Database

The user service is running inside a container but it has configured to connect to the database which is running in the Docker host machine.

Pointing to host db

Pointing to host db

The database configuration of userserivce 

The localhost on the datasource URL tells userservice to search the database inside the container network but it is not there. Let’s configure the datasource to connect to the Postgres which is outside docker. For mac users it simple to change.

Point Application Container to Container Database

Point Application Container to Container Db

Point Application Container to Container Db

You need to inspect the container to get the Postgres container IP address and add on the datasource URL

 $docker instpect postgres 

Container IP would change each time when container restarted

Docker Compose to Create Multiple Containers Together

Define multiple docker container applications in a docker-compose.yml file to configure and running docker applications together.  In this case, you can use the postgres service name on datasource URL to point the application to the container database. 


 Navigate terminal to the same directory of docker-compose.yml file and run the following command:

docker-compose up -d 

View the created containers:

 docker ps 

Important things to remember to containerize applications are isolation, network, security, and monitoring.

Source link

laravel helpers

Create Custom Laravel Helper Methods

laravel helpers

Hi All, this is Adi, with another Laravel article. I wanted to take some time to explain what Laravel’s Helper methods are and how you can create your own ones. I was never a big fan of creating my own custom helper methods when I started with Laravel, but with time, I have started using them more often and these days there’s no Laravel project without customer helpers.

Let’s get started.

What Are Laravel Helpers

Laravel Helper methods are “plain old” PHP functions, that you can call from any part of your Laravel Application. You may have already used a lot of Laravel’s built-in helper methods like route(), url(), view(), dd(), and a list of others. You do not have to require any PHP files or reference any namespace to use them, they are magically available in all parts of your application. I’ll explain more about the magic part in just a moment.

Here are a few use cases for creating custom helper methods. To call other utility classes, if there’s a generic logic that’s used multiple times in your code you might want to extract it out into a helper. I extensively use helpers to make formatting easier in my Blade view, such as automatically adding a currency symbol before a number or to format a number in a certain digit grouping or set dates in your application to use the same format on display.

Now let’s see how simple it is to create custom Helper methods.

Creating Custom Helpers

It is as simple as creating a file somewhere in the app directory and inform composer to auto-load it when the application starts, simple is it not. I usually have all my helper functions in a single file called Helpers.php in the app/Utils/ folder, this is where I store all my utility classes but you can create this file anywhere in the app directory you see fit. Then, you need to register this file in your composer.json file that’s at the root of your project. For reference, you can check out how the Laravel framework registers it’s helpers here.

And that’s it. Make sure to run this command composer dump-autoload and restart your application. This will make sure that the Helper.php is loaded when Laravel is started. Now let’s define your first helper method in the Helper.php file.

This say_hi method can now be accessed in any part of your application. It’s a simple example but you can make it as complex as needed.


I hope you found this article on Laravel helpful. Laravel Helpers are such a handy feature that saves a lot of time. Hope you see the reasons to create your custom ones.

Useful Resources:

Source link

Post image

Looking for guidance on how to build a website with a sideba…

Hello, I am looking for guidance on how to build a web app that would be similar to the mock-up.

It would be similar to Shopify in terms of ease of development for the user.

  • A user would have a single page profile

  • Can create their own tab names

  • The user can upload an optional cover image and an optional avatar

  • The user would be able to choose if the avatar is left, right, or center

  • The user can choose whether their name and intro is left, right, or center (also optional)

  • The user can choose a background image or color

  • They can change the font style and size

Creating the post would be handled on a separate page. This page would more so be for editing the look and feel.

I have some experience with Flask / Python and would likely build the backend and user authentication that way. I am confused about how to create the front end part so a user could simply modify the design of their profile similar to a Shopify or Squarespace.

My question is: Do you know of any guides or tutorials that discuss a similar feature that allows a user to control the design / CSS of their profile? Or what it is called so I can look it up further?

Post image

Source link

Sign Up

Create a Login System Using HTML, PHP, and MySQL

This is a tutorial for creating a login system with the help of HTML, PHP, and MySQL. Your website needs to be dynamic and your visitors need to have instant access to it. Therefore, they want to log in as many times as possible. The login authentication system is very common for any web application. It allows registered users to access the website and members-only features. It is also helpful when we want to store information for users. It covers everything from shopping sites, educational sites, and membership sites, etc.

This tutorial is covered in 4 parts.

  1. Sign up System
  2. Login System
  3. Welcome Page
  4. Logout Script

1) Building a Sign-up system

In this part, We will create a signup system that allows users to create a new account to the system. Our first step is to create a HTML registration form. The form is pretty simple to create. It only asks for a name, email, password, and confirm password. Email addresses will be unique for every user. Multiple accounts for the same email address are not allowed. It will show an error message to the users who try to create multiple accounts with the same email address.

Step 1: Creating Registration Form in HTML

We will create a PHP file named register.php with the following code in it. This is a simple HTML form with some basic validation. If you are not familiar with HTML then you can get it from many online sites who give ready-made html5 login form templates.

The output of the above HTML form will look like this.

Sign Up

Sign Up

All the input fields are required by adding the "required" attribute which is the default HTML attribute. The use of type="email" will validate the email address provided by users and gives an error if the email address is not valid. For the registration form, we have used bootstrap for rapid development. If you want to save your time on HTML code you can always use some free html5 templates for your project.

Step 2: Creating the MySQL Database Table

You will need to create a new database with any suitable name you want. After that please execute the below SQL query to create the user’s table inside your newly created MySQL database.

Step 3: Creating Database Configuration File

Now, we have created the users table. Let’s create a new PHP file named config.php to connect with the MySQL database. Paste the following code in the config.php file and change the database name to whatever you choose while creating the database.

Step 4: Creating a Session File

Let’s create a file named session.php. In this file, we will start the session and check if a user is already logged in, if yes then we will redirect the user to welcome.php file.

Step 5: Create Registration Form in PHP

Finally, it’s time to create a PHP code that allows users to register their accounts into the system. This PHP code will alert users with an error if any user is already registered with the same email address.

Replace the following code in the register.php file.

Once user click on submit button it will check if $_SERVER["REQUEST_METHOD"] == "POST" and $_POST['submit'] a variable has been set. For security concerns, we always suggest not to store the password as plain text in the database. We have used password_hash() function which creates a new password hash using a strong one-way hashing algorithm.

The above PHP script will validate that no user is registered with the same email address and also validate the password. After validation is confirmed we store the user-provided information in the users’ table and alert the user that registration was successful.

2) Building a Login System

In this part, we will create a login form to allow users to access the restricted area of the system. In our case, the restricted area is a welcome page which we will cover in the next part.

Step 1: Creating a Login Form in HTML

Below is the Login Form in HTML. Paste it in a file named login.php

The output of the above code will look like this



Step 2: Creating a Login System in PHP

After creating the login form in HTML, we will write a code to validate login credentials. On form submit we will check that the email and password are filled. If they filled then we will execute a SELECT query to find the record in a database on the basis of email and password. If any record found, then we will store the "userID" in session and the user is redirected to the welcome.php file, otherwise, the user is alerted with an error message.

Let’s replace the following code in the login.php file.

3) Creating a Welcome Page

Below is the code for the welcome.php file. Users will be redirected to this page after a successful login process. We have added some code at the top of the page to check if the user is not logged in, then redirect the user to the login page.

Let’s create a welcome.php file and paste the following code in it.

4) The Logout Script

Finally, Let’s create a logout.php file with the following code in it.

Once the user clicks on the Log Out link, the above script, will be called to destroy the session and redirect the user to the login.php file.


In this tutorial, I explained how you can create a Login System using HTML, PHP, and MySQL. Once you understand how simple it is to create a login system you can add other features like reset password, forgot password, verify email address, edit user’s profile, etc.

Source link

How can i achieve this effect? Work by "another_design"

How can i achieve this effect? Work by "another_design&…

How can i achieve this effect? Work by "another_design"

Hi guys

So i was diggin behance and then i came across this beautiful design from another_design.

And now im wondering, is there like a filter or effect that creates those squares or is every square "handmade".

submitted by /u/cometopluto

Source link

WordPress Block Transforms | CSS-Tricks

WordPress Block Transforms | CSS-Tricks

This has been the year of Gutenberg for us here at CSS-Tricks. In fact, that’s a goal we set at the end of last year. We’re much further along that I thought we’d be, authoring all new content in the block editor¹, enabling the block editor for all content now. That means when we open most old posts, we see all the content in the “Classic” block. It looks like this:

A post written on CSS-Tricks before we were using the block editor.

The entire contents of the post is in a single block, so not exactly making any use of the block editor. It’s still “visual,” like the block editor, but it’s more like the old visual editor using TinyMCE. I never used that as it kinda forcefully mangled HTML in a way I didn’t like.

This is the #1 thing I was worried about

Transforming a Classic block into new blocks is as trivial as selecting the Classic block and selecting the “Convert to Blocks” option.

Select the option and the one block becomes many blocks.

How does the block editor handle block-izing old content, when we tell it to do that from the “Convert to Blocks” option? What if it totally screws up content during the conversion? Will we ever be able to switch?

The answer: it does a pretty darn good job. But… there are still issues. Not “bugs” but situations where we have custom HTML in our old content and it doesn’t know what to do with it — let alone how to convert it into exactly the blocks we wish it would. There is a way!

Basic Block Transforms

That’s where this idea of “Block Transforms” comes in. All (well, most?) native blocks have “to” and “from” transformations. You’re probably already familiar with how it manifests in the UI. Like a paragraph can transform “to” a quote and vice versa. Here’s a super meta screenshot of this very paragraph:

Those transforms aren’t magic; they are very explicitly coded. When you register a block, you specify the transforms. Say you were registering your own custom code block. You’d want to make sure that you could transform it…

  • From and to the default built-in code block, and probably a handful of others that might be useful.
  • Back to the built-in code block.

Which might look like:

registerBlockType("my/code-block", {
  title: __("My Code Block"),
  transforms: {
    from: [
        type: "block",
        priority: 7,
        blocks: ["core/code", "core/paragraph", "core/preformatted"],
        transform: function (attributes) {
          return createBlock("my/code-block", {
            content: attributes.content,
    to: [
        type: "block",
        blocks: ["core/code"],
        transform: ({ content }) => createBlock("core/code", { content }),

Those are transforms to and from other blocks. Fortunately, this is a pretty simple block where we’re just shuffling the content around. More complex blocks might need to pass around more data, but I haven’t had to deal with that yet.

The more magical stuff: Block Transforms from raw code

Here’s the moment of truth for old content:

The “Convert to Blocks” option.

In this situation, blocks are being created not from other blocks, but from raw code. Quite literally, the HTML is being looked at and choices are being made about what blocks to make from chunks of that HTML. This is where it’s amazing the block editor does such a good job with the choices, and also where things can go wrong and it can fail, make wrong block choices, or mangle content.

In our old content, a block of code (a super very important thing) in a post would look like this:

<pre rel="JavaScript"><code class="language-javascript" markup="tt">
  let html = `<div>cool</div>`;

Sometimes the block conversion would do OK on those, turning it into a native code block. But there were a number of problems:

  1. I don’t want a native code block. I want that to be transformed into our own new code block (blogged about that here).
  2. I need some of the information in those attributes to inform settings on the new block, like what kind of code it is.
  3. The HTML in our old code blocks was not escaped and I need it to not choke on that.

I don’t have all the answers here, as this is an evolving process, but I do have some block transforms in place now that are working pretty well. Here’s what a “raw” transform (as opposed to a “block” transform) looks like:

registerBlockType("my/code-block", {
  title: __("My Code Block"),
  // ...
  transforms: {
    from: [
        type: "block",
        priority: 7,
        // ...
        type: "raw",
        priority: 8,
        isMatch: (node) =>
          node.nodeName === "PRE" &&
          node.children.length === 1 &&
          node.firstChild.nodeName === "CODE",
        transform: function (node) {
          let pre = node;
          let code = node.querySelector("code");

          let codeType = "html";
          if (pre.classList.contains("language-css")) {
            codeType = "css";
          if (pre.getAttribute("rel") === "CSS") {
            codeType = "css";
          if (pre.classList.contains("language-javascript")) {
            codeType = "javascript";
          if (code.classList.contains("language-javascript")) {
            codeType = "javascript";
          // ... other data wrangling...

          return createBlock("csstricks/code-block", {
            content: code.innerHTML,
            codeType: codeType,
    to: [
      // ... 
   // ...


That isMatch function runs on every node in the HTML it finds, so this is the big opportunity to return true from that in the special situations you need to. Note in the code above that I’m specifically looking for HTML that looks like <pre ...><code ...>. When that matches, the transform runs, and I can return a createBlock call that passes in data and content I extract from the node with JavaScript.

Another example: Pasting a URL

“Raw” transforms don’t only happen when you “Convert to Blocks.” They happen when you paste content into the block editor too. You’ve probably experienced this before. Say you have copied some table markup from somewhere and paste it into the block editor -— it will probably paste as a table. A YouTube URL might paste into an embed. This kind of thing is why copy/pasting from Word documents and the like tend to work so well with the block editor.

Say you want some special behavior when a certain type of URL is pasted into the editor. This was the situation I was in with our custom CodePen Embed block. I wanted it so if you pasted a URL, it would use this custom block, instead of the default embed.

This is a “from” transform that looks like this:

  type: "raw",
  priority: 8, // higher number to beat out default
  isMatch: (node) =>
    node.nodeName === "P" &&

  transform: function (node) {
    return createBlock("cp/codepen-gutenberg-embed-block", {
      penURL: node.innerText,
      penID: getPenID(node.innerText), // helper function


Is it messy? A little. But it’s as powerful as you need it to be. If you have an old site with lots of bespoke HTML and shortcodes and stuff, then getting into block transforms is the only ticket out.

I’m glad I went to WPBlockTalk and caught K. Adam White’s talk on shortcodes because there was just one slide that clued me into that this was even possible. There is a little bit of documentation on it.

One thing I’d like to figure out is if it’s possible to run these transforms on all old content in the database. Seems a little scary, but also like it might be a good idea in some situations. Once I get my transformations really solid, I could see doing that so any old content ready-to-go in the block editor when opening it up. I just have no idea how to go about it.

I’m glad to be somewhat on top of this though, as I friggin love the block editor right now. It’s a pleasure to write in and build content with it. I like what Justin Tadlock said:

The block system is not going anywhere. WordPress has moved beyond the point where we should consider the block editor as a separate entity. It is an integral part of WordPress and will eventually touch more and more areas outside of the editing screen.

It’s here to stay. Embracing the block editor and bending it to our will is key.

Source link