Blade Templates – Escaping text and allowing new lines.
Before getting to the solution, It is important to understand the PHP and Laravel helper function which we are going to use.
nl2br() php function is used to convert “\n” (new line character) into “
” tag so the browser can display the next sentence in a new line.
echo nl2br(“This is a sample text.\nIt has multiple lines.\nContains new line characters.”);
Output:
Escaping text and allowing new line
In this topic we will learn how we can use Laravel’s e() (escape helper function) and PHP’s nl2br() function to escape and convert HTML tags into entities to prevent XSS attacks and display sentences in new lines.
{!! nl2br(e($userInput)) !!}
This is how our code will look like. Let’s see the example source code in the next slide.
We are using {!! !!} blade echo syntax because we are already escaping the special characters using e() helper so no need to use.
Example:
<div> @php $textClass = "text-blue-100 text-lg"; $userInput = "<script>alert('Hello')</script>\nThis is a sample text.\nIt has multiple lines.\nContains new line characters."; @endphp <div class="bg-gray-200 m-5 p-5 rounded-lg"> {{-- Escaping text and display in new line. (We are using {!! !!} syntax because we already escaping special characters using e() helper) --}} <div class="bg-gray-900 m-5 p-5 rounded-lg"> <p class="{{ $textClass }}"> {!! nl2br(e($userInput)) !!} </p> </div> </div> </div>
In the example we have an input field in which the user can add “\n” (new line character) and HTML tags as well so we need to display it on the browser accordingly. So in this case an attacker can easily add Javascript to do XSS attack. In our example the user has added Javascript.
<script> alert('Hello') </script>
To prevent this type of insertion we are using e() and to display in a new line we are using nl2br().
Work with our skilled Laravel developers to accelerate your project and boost its performance.
Hire Laravel Developer