An introduction to Twig templating – Creating a Sentiment Analysis app
We will be building a simple app which takes from the user the id/name of a Facebook page (the name written in the URL when visiting a Facebook page) and shows some statistics related to the sentiment of the last 100 posts of that Facebook page. It shows whether the page is positive, negative or neutral, how many of the last one hundred posts are considered positive, negative or neutral and it pinpoint the total distribution of positivity, negativity and neutrality in those posts.
In this last piece, we are going to show the sentiments of the collected using Facebook’s PHP SDK posts of an arbitrary page using Twig.
Our file which is served to users loads the Composer dependencies (Composer is a dependanc manager for PHP from which you can import third-party libraries – https://getcomposer.org/). Then, it checks whether a page-name GET parameter is set. If it is set, then the user has submitted the form and we would have to analyze the sentiments of its posts.
See Also: An introduction to sentiment analysis with phpInsight – Creating a Sentiment Analysis app
require_once 'vendor/autoload.php'; if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET['page-name'])) { // user wants to view sentiment require_once("analysis.php"); $analysis = new pageAnalysis($_GET['page-name']); }
Following that, we instantiate the Twig loader, indicating that the templates are going to be in the file system and passing an argument to the folder where our templates would be.
$loader = new Twig_Loader_Filesystem('templates');
Thus, our folder where Twig should start searching for templates is called templates.
Next, we actually set up Twig for displaying the templates by calling Twig_Environment, passing it the loader variable and any options. In terms of options, we set up the path to the view caches to be the subfolder cache in our templates directory. The cached view will be shown whenever a user accesses the same page with the same parameters twice.
twig = new Twig_Environment($loader, array( 'cache' => 'templates/cache' ));
Then, we build up the arguments for the view. If a sentiment analysis has been carried out – there should be arguments passed to the view. If there is no error, the arguments are the resulting pageAnalysis object and the name of the page. If there is an error, then we only set up the error as an argument. You could use ternary operators to manage the checks instead.
$args = array(); if (isset($analysis)) { if (!$analysis->error) { $args = array("analysis" => $analysis, 'pageName' => $_GET['page-name']); } else { $args = array("error" => $analysis->error); } }
Finally, we display the index.html view (which should be located in the templates folder that we pointed Twig to) with Twig and pass it the necessary arguments.
echo $twig->render(‘index.html’, $args);
Using Twig’s templating capabilities, we check if there was an argument called error passed to the template and display its value – if there was an error. Using {% %} we can run conditionals, loops and other logic while using {{ }} we display a variable, an argument, etc.. The |e filter in the context of error|edisplays the error argument while escaping it.
{% if error %} <p class="alert alert-danger text-center"> {{ error|e }} </p> {% endif %} <form action="" method="get"> <label for="page-name">The Facebook Page's Name: </label> <input type="text" id="page-name" class="form-control" name="page-name" placeholder="ProgrammerCreatesLife"> <button class="btn btn-lg btn-default" type="submit">View Sentiment</button> </form>
Then, no matter the arguments, we display a form where the users can write a page id, submit it and see new sentiment analysis results.
Following that, we start displaying the results of the sentiment analysis but only if there is one to display. We display the escaped name of the page that the user wrote and show its dominant sentiment. We also display the sentiment in different color by providing different classes for positive, negative and neutral sentiments.
{% if analysis %} <h1 class="text-center">The Facebook page <span class="lead">{{ pageName|e }}</span> is mostly <span class="label label-lg label-{{analysis.dominantSentiment == 'positive' ? 'success' : analysis.dominantSentiment == 'neutral' ? 'default' : 'warning'}}"> {{ analysis.dominantSentiment }}</span></h1>
We display the number of positive, neutral, and negative posts by adding a HTML5 progress tag for each sentiment, we set the maximum value of the progress bar to be the total number of posts and the current value to be the positive posts for the positive progress bar, the negative for the second negative progress bar and so on. We also display a label which shows the actual numbers behind the progress bar.
<h1>Number of Positive, Negative and Neutral Posts (for 100 posts)</h1> <div id="post-positivity"> <p class="lead">Positivity</p> <progress max="{{ analysis.posts.data|length }}" value="{{ analysis.dominantSentiments.pos ?: 0 }}" ></progress> <span class="label label-info label-lg"> ( {{ analysis.dominantSentiments.pos }} post(s) of {{ analysis.posts.data|length}} ) </span> </div>
After we repeat the above process for the negative and neutral sentiments, we employ a similar technique to display the total distribution of positivity, negativity and neutrality on the Facebook page.
<h1>Total Distribution of Positivity, Negativity and Neutrality for the Facebook page <span class="label label-lg label-default">{{ pageName|e }}</span></h1> <div id="positvity"> <p class="lead">Positivity</p> <progress max="{{ analysis.maximumTotalSentiment|e }}" value="{{ analysis.totalSentiments.pos }}" ></progress> <span class="label label-info label-lg"> ( score {{ analysis.totalSentiments.pos }} of {{ analysis.maximumTotalSentiment|e }} ) </span> </div>
So, besides learning a thing or two about templating with Twig, we have created a simple mini-sentiment analysis app that can inform users on the mood surrounding different Facebook pages.
Tutorial Categories: