Author: Fabien Potencier (fabien@symfony.com)
Inheritance: implements Symfony\Bundle\FrameworkBundle\Templating\EngineInterface, implements Symfony\Component\Templating\StreamingEngineInterface
コード例 #1
0
ファイル: TwigMessage.php プロジェクト: rodw1995/vind-niet
 /**
  * Set HTML content to the twig template
  *
  * @return Message
  * @throws \Exception
  * @throws \Twig_Error
  */
 public function render()
 {
     $html = $this->twigEngine->render($this->templateName, $this->arguments);
     $this->setText($this->replacePlaceholdersWithArguments($this->getText()));
     $this->setSubject($this->replacePlaceholdersWithArguments($this->getSubject()));
     return $this->setHtml($html);
 }
コード例 #2
0
 /**
  * @param $view
  * @param $parameters
  * @return string
  */
 public function render($view, $parameters)
 {
     if (is_null($this->templating)) {
         $this->templating = $this->container->get('templating');
     }
     return $this->templating->render($view, $parameters);
 }
コード例 #3
0
 /**
  * @param FormSubmission $submission The submission
  * @param string         $from       The from address
  * @param string         $to         The to address(es) seperated by \n
  * @param string         $subject    The subject
  */
 public function sendContactMail(FormSubmission $submission, $from, $to, $subject)
 {
     $toArr = explode("\r\n", $to);
     /* @var $message Swift_Mime_Message */
     $message = Swift_Message::newInstance()->setSubject($subject)->setFrom($from)->setTo($toArr);
     $message->setBody($this->templating->render('KunstmaanFormBundle:Mailer:mail.html.twig', array('submission' => $submission, 'host' => $this->container->get('request')->getScheme() . '://' . $this->container->get('request')->getHttpHost())), 'text/html');
     $this->mailer->send($message);
 }
コード例 #4
0
 /**
  * @param \FTC\Bundle\CodeBundle\Event\SnippetPayload $event
  */
 public function onNewSnippet(SnippetPayload $event)
 {
     $recipient = $event->getSnippet()->getComment()->getEntry()->getAuthor();
     $subject = "New code snippet on FixThatCode.com";
     $body = $this->templating->render('FTCWebBundle:Email:notification_snippet.html.twig', array('entry' => $event->getSnippet()->getComment()->getEntry(), 'snippet' => $event->getSnippet()));
     $email = $this->createEmail($recipient, $subject, $body);
     $this->mailer->send($email);
 }
コード例 #5
0
 /**
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function success(Request $request)
 {
     $id = $request->get('id');
     $charged = $request->get('charged');
     $created = $request->get('created');
     $currency = $request->get('currency');
     return $this->templating->renderResponse($this->stripeParameters['success_template'], ['id' => $id, 'charged' => $charged, 'created' => $created, 'currency' => $currency]);
 }
コード例 #6
0
 /**
  * @Route("/sitemap.xml", name="sitemap_route", defaults={"_format"="xml"})
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getSitemapAction()
 {
     /** @var PageEleveurBranch[] $pageEleveurBranchess */
     $pageEleveurBranches = $this->peBranchRepository->findAll();
     $this->logger->info('generation de la sitemap', ['count' => count($pageEleveurBranches)]);
     $this->logger->debug('contenu de la sitemap', ['pageEleveurBranches' => $pageEleveurBranches]);
     return $this->templating->renderResponse('sitemap.xml.twig', ['pageEleveurBranches' => $pageEleveurBranches]);
 }
コード例 #7
0
 /**
  * Renders top menu with child items.
  *
  * @param string $template
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getChildNodesAction($template)
 {
     $locationSearchResults = $this->searchService->findLocations($this->menuQueryType->getQuery());
     $menuItems = [];
     foreach ($locationSearchResults->searchHits as $hit) {
         $menuItems[] = $hit->valueObject;
     }
     return $this->templating->renderResponse($template, ['menuItems' => $menuItems], new Response());
 }
コード例 #8
0
 /**
  * @DI\Observe("widget_innova_path_widget_configuration")
  *
  * @param ConfigureWidgetEvent $event
  */
 public function onConfigure(ConfigureWidgetEvent $event)
 {
     $instance = $event->getInstance();
     $config = $this->pathManager->getWidgetConfig($instance);
     $form = $this->formFactory->create('innova_path_widget_config', $config);
     $content = $this->twig->render('InnovaPathBundle:Widget:config.html.twig', ['form' => $form->createView(), 'instance' => $instance, 'tags' => $this->tagManager->getPlatformTags()]);
     $event->setContent($content);
     $event->stopPropagation();
 }
 /**
  * @param UserEvent $event
  * @throws \Exception
  * @throws \Twig_Error
  */
 public function onResettingRequestSuccess(UserEvent $event)
 {
     $user = $event->getUser();
     $params = $event->getParams();
     $url = $this->router->generate($params[$event::PARAM_RESETTING_EMAIL_ROUTE], array('token' => $user->getConfirmationToken()), true);
     $message = \Swift_Message::newInstance()->setSubject($this->translator->trans('security.resetting.request.email.subject'))->setFrom($this->parameter->get($params[$event::PARAM_RESETTING_EMAIL_FROM]))->setTo($user->getEmail())->setBody($this->twigEngine->render($params[$event::PARAM_RESETTING_EMAIL_TEMPLATE], array('complete_name' => $event->getSecureArea()->getCompleteName(), 'url' => $url)));
     $this->mailer->send($message);
     $this->flashBag->add(FlashBagEvents::MESSAGE_TYPE_SUCCESS, $this->translator->trans('security.resetting.request.check_email', array('user_email' => $user->getObfuscatedEmail())));
 }
コード例 #10
0
 public function renderStatistics(TwigEngine $tpl)
 {
     $labels = [];
     $data = [];
     foreach ($this->data as $area) {
         $labels[] = '\'' . addslashes($area['name']) . '\'';
         $data[] = $area['sum'];
     }
     return $tpl->render('WioEdkBundle:Stats:biggest-areas-chart.js.twig', array('labels' => implode(',', $labels), 'data' => implode(',', $data)));
 }
コード例 #11
0
 public function renderStatistics(TwigEngine $tpl)
 {
     $labels = [];
     $data = [];
     foreach ($this->data as $item) {
         $labels[] = '"' . addslashes($item['name']) . '"';
         $data[] = $item['count'];
     }
     return $tpl->render('CantigaCoreBundle:Stats:area-per-status.js.twig', array('labels' => implode(', ', $labels), 'data' => implode(', ', $data)));
 }
コード例 #12
0
 /**
  * @param $subject
  * @param $template
  * @param $data
  * @param Request $request
  * @return mixed
  * @throws \Doctrine\ORM\ORMException
  * @throws \Doctrine\ORM\OptimisticLockException
  * @throws \Doctrine\ORM\TransactionRequiredException
  * @throws \Exception
  * @throws \Twig_Error
  *
  * @return \Swift_Message
  */
 public function createMessage($subject, $template, $data, Request $request = null)
 {
     $history = null;
     if ($request && $request->cookies->has('tracker_id')) {
         /** @var \keltanas\Bundle\TrackingBundle\Entity\History $history */
         $history = $this->em->find('keltanasTrackingBundle:History', $request->cookies->get('tracker_id'));
     }
     $message = $this->mailer->createMessage()->setSubject($subject)->setFrom($this->from)->setTo($this->to)->setBody($this->templating->render($template, ['data' => $data, 'history' => $history]), 'text/html', 'utf-8');
     return $message;
 }
コード例 #13
0
 /**
  * @inheritDoc
  */
 public function __invoke(UserRegisterCommand $command)
 {
     $user = $command->getUser();
     $user->setUsername($user->getEmail());
     $em = $this->registry->getManager();
     $em->persist($user);
     $em->flush();
     $hash = password_hash($user->getSalt(), PASSWORD_DEFAULT);
     $message = \Swift_Message::newInstance()->setSubject('Brökkes Account validation')->setFrom('*****@*****.**')->setTo($user->getEmail())->setBody($this->templating->render(':Email:registration.html.twig', ['hash' => urlencode($hash), 'user' => $user]), 'text/html')->addPart($this->templating->render(':Email:registration.txt.twig', ['hash' => urlencode($hash), 'user' => $user]), 'text/plain');
     $this->mailer->send($message);
 }
コード例 #14
0
 /**
  * Send the notifications.
  *
  * @param int       $days
  * @param User[]    $users
  * @param Journal[] $journals
  */
 protected function sendReminders($days, $users, $journals)
 {
     $notification = $this->templating->render('AppBundle:HealthCheck:reminder.txt.twig', array('journals' => $journals, 'days' => $days));
     $mailer = $this->getContainer()->get('mailer');
     foreach ($users as $user) {
         $message = Swift_Message::newInstance('Automated reminder from the PKP PLN', $notification, 'text/plain', 'utf-8');
         $message->setFrom('*****@*****.**');
         $message->setTo($user->getEmail(), $user->getFullname());
         $mailer->send($message);
     }
 }
コード例 #15
0
 /**
  * @param AMQPMessage $msg
  * @return bool
  */
 public function execute(AMQPMessage $msg)
 {
     $post = $this->serializer->deserialize($msg->body, 'AppBundle\\Entity\\Post', 'json');
     $targetPath = $this->container->get('kernel')->getRootDir() . '/../web/downloads/pdf/' . $post->getPdfName() . '.pdf';
     $this->container->get('knp_snappy.pdf')->generateFromHtml($this->templating->render('RabbitMQBundle::pdf_post_view.html.twig', array('post' => $post)), $targetPath);
     if (file_exists($targetPath)) {
         return true;
     } else {
         return false;
     }
 }
コード例 #16
0
ファイル: TwigEngineTest.php プロジェクト: notbrain/symfony
 public function testEvalutateWithoutAvailableRequest()
 {
     $environment = $this->getTwigEnvironment();
     $container = new Container();
     $engine = new TwigEngine($container, $environment, new GlobalVariables($container));
     $template = $this->getMock('\\Twig_TemplateInterface');
     $environment->expects($this->once())->method('loadTemplate')->will($this->returnValue($template));
     $container->set('request', null);
     $engine->render('name');
     $globals = $environment->getGlobals();
     $this->assertEmpty($globals['app']->getRequest());
 }
コード例 #17
0
 /** 
  * @DI\Observe(AppConstants::EMAIL_NEW_USER)
  */
 public function sendNewUserEmail(PasswordEvent $event)
 {
     $password = $event->getPassword();
     $user = $event->getUser();
     $message = \Swift_Message::newInstance()
         ->setSubject('New User Password')
         ->setFrom('*****@*****.**')
         ->setTo($user->getEmail())
         ->setBody( $this->template->render('AppBundle:Email:newuser.html.twig', ['password' => $password] ),'text/html');
     
     $this->mailer->send($message);
 }
コード例 #18
0
 /**
  * Renders top menu with child items.
  *
  * @param string $template
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function getChildNodesAction($template)
 {
     $query = new LocationQuery();
     $query->query = $this->menuCriteria->generateChildCriterion($this->locationService->loadLocation($this->topMenuLocationId), $this->configResolver->getParameter('languages'));
     $query->sortClauses = [new SortClause\Location\Priority(LocationQuery::SORT_ASC)];
     $query->performCount = false;
     $content = $this->searchService->findLocations($query);
     $menuItems = [];
     foreach ($content->searchHits as $hit) {
         $menuItems[] = $hit->valueObject;
     }
     return $this->templating->renderResponse($template, ['menuItems' => $menuItems], new Response());
 }
コード例 #19
0
 /**
  * @Route("/newsletter/new", name="newsletter_new")
  *
  * @return Response
  *
  * @throws \Exception
  * @throws \Twig_Error
  */
 public function newAction(Request $request)
 {
     $resolvedForm = $this->formFactory->create(new NewsletterCampaignFormType());
     if ($request->isMethod("POST")) {
         $resolvedForm->handleRequest($request);
         if ($resolvedForm->isValid()) {
             $newsletterCampaign = $resolvedForm->getData();
             $this->newsletterCampaignManager->save($newsletterCampaign);
             $this->session->getFlashBag()->add('message', 'Saved!');
         }
     }
     return new Response($this->twig->render('AppBundle:Newsletter:new.html.twig', array('form' => $resolvedForm->createView(), '')));
 }
コード例 #20
0
 /**
  * @param LifecycleEventArgs $args
  */
 public function postPersist(LifecycleEventArgs $args)
 {
     $document = $args->getDocument();
     if (!$document instanceof Event) {
         return;
     }
     $location = $document->getPlace()->getLocation();
     $subscribers = $this->subscriberRepository->createQueryBuilder()->field('location')->near((double) $location->getLongitude(), (double) $location->getLatitude())->maxDistance(5 / 111.12)->getQuery()->execute();
     foreach ($subscribers as $subscriber) {
         $body = $this->templating->render('ApiBundle:Email:subscriber.html.twig', ['event' => $document]);
         $message = \Swift_Message::newInstance()->setSubject('Ping - New event on you area !')->setFrom('*****@*****.**')->setTo($subscriber->getEmail())->setBody($body, 'text/html');
         $this->mailer->send($message);
     }
 }
コード例 #21
0
 /**
  * @param PlatformContentItemDetailsEvent $event
  *
  * @DI\Observe("administration_analytics_platform_content_item_details_portfolio")
  */
 public function onPlatformContentItemDetailsPortfolio(PlatformContentItemDetailsEvent $event)
 {
     $this->entityManager->getFilters()->disable('softdeleteable');
     $countPortfolio = $this->portfolioManager->countAll();
     $countDeletedPortfolio = $this->portfolioManager->countAllDeleted();
     $countClosedPortfolio = 0;
     $countOpenPortfolio = 0;
     $countPrivatePortfolio = 0;
     $countPlatformPortfolio = 0;
     $countPortfolioByVisibilityStatuss = $this->portfolioManager->countAllByVisibilityStatus();
     foreach ($countPortfolioByVisibilityStatuss as $countPortfolioByVisibilityStatus) {
         switch ($countPortfolioByVisibilityStatus['visibility']) {
             case Portfolio::VISIBILITY_NOBODY:
                 $countClosedPortfolio = $countPortfolioByVisibilityStatus['number'];
                 break;
             case Portfolio::VISIBILITY_EVERYBODY:
                 $countOpenPortfolio = $countPortfolioByVisibilityStatus['number'];
                 break;
             case Portfolio::VISIBILITY_USER:
                 $countPrivatePortfolio = $countPortfolioByVisibilityStatus['number'];
                 break;
             case Portfolio::VISIBILITY_PLATFORM_USER:
                 $countPlatformPortfolio = $countPortfolioByVisibilityStatus['number'];
                 break;
             default:
                 throw new \Exception();
                 //not supposed to happen, but hey who knows ;-)
         }
     }
     $countPortfolioByVisibilityStatusGraphData = [['name' => 'closed_mode_portfolio', 'value' => $countClosedPortfolio], ['name' => 'open_mode_portfolio', 'value' => $countOpenPortfolio], ['name' => 'private_mode_portfolio', 'value' => $countPrivatePortfolio], ['name' => 'platform_mode_portfolio', 'value' => $countPlatformPortfolio]];
     $event->setContent($this->twig->render('IcapPortfolioBundle:analytics:platform_content_item_details.html.twig', ['countPortfolio' => $countPortfolio, 'countClosedPortfolio' => $countClosedPortfolio, 'countOpenPortfolio' => $countOpenPortfolio, 'countPrivatePortfolio' => $countPrivatePortfolio, 'countPlatformPortfolio' => $countPlatformPortfolio, 'countDeletedPortfolio' => $countDeletedPortfolio, 'portfolioRepartitionStatuss' => $countPortfolioByVisibilityStatusGraphData]));
     $event->stopPropagation();
 }
コード例 #22
0
 /**
  * {@inheritdoc}
  */
 public function render($name, array $parameters = array())
 {
     $e = $this->stopwatch->start(sprintf('template.twig (%s)', $name), 'template');
     $ret = parent::render($name, $parameters);
     $e->stop();
     return $ret;
 }
コード例 #23
0
ファイル: TreeManager.php プロジェクト: octava/cms
 /**
  * Метод получает из вьювера HTML код дерева
  *
  * @return string HTML код
  */
 public function get()
 {
     if (!$this->sendData2Viewer()) {
         return null;
     }
     return $this->twigEngine->render($this->treeTemplate, $this->viewData);
 }
コード例 #24
0
 /**
  * @param string $type
  * @param array $params
  */
 protected function sendNotice($type, array $params)
 {
     $notice = new Notice();
     $notice->setType($type);
     $notice->setMessage($this->templating->render('AnimeDbCatalogBundle:Notice:messages/' . $type . '.html.twig', $params));
     $this->em->persist($notice);
 }
コード例 #25
0
 /**
  * @param Operation $operation
  * @return \Symfony\Component\HttpFoundation\Response
  * @throws \Exception
  */
 public function readAction(Operation $operation)
 {
     $newsItem = $this->contentService->getNewsItemByOperation($operation);
     $activity = $operation->getActivity();
     $locationModuleIdentifier = $activity->getLocation()->getLocationModule()->getIdentifier();
     $isCompanyPageShare = 'campaignchain-linkedin-page' == $locationModuleIdentifier;
     $isLive = true;
     if (!$newsItem->getLinkedinData()) {
         $connection = $this->restClient->getConnectionByActivity($activity);
         /*
          * Below calls to the Linkedin REST API will throw errors if the
          * Linkedin App has not been approved by Linkedin as part of their
          * partner program.
          */
         try {
             if ($isCompanyPageShare) {
                 $response = $connection->getCompanyUpdate($activity, $newsItem);
             } else {
                 $response = $connection->getUserUpdate($activity, $newsItem);
             }
             if (!is_null($response)) {
                 $newsItem->setLinkedinData($response);
                 $this->em->persist($newsItem);
                 $this->em->flush();
             } else {
                 $isLive = false;
             }
         } catch (\Exception $e) {
             $isLive = true;
         }
     }
     return $this->templating->renderResponse('CampaignChainOperationLinkedInBundle::read.html.twig', array('page_title' => $activity->getName(), 'news_item' => $newsItem, 'activity' => $activity, 'is_live' => $isLive, 'is_company' => $isCompanyPageShare));
 }
コード例 #26
0
 /**
  * Send a deposit to LOM via HTTP.
  *
  * @param Deposit $deposit
  *
  * @return bool true on success
  */
 public function createDeposit(Deposit $deposit)
 {
     $this->serviceDocument($deposit->getJournal());
     $xml = $this->templating->render('AppBundle:SwordClient:deposit.xml.twig', array('title' => 'Deposit from OJS part ' . $deposit->getAuContainer()->getId(), 'publisher' => 'Public Knowledge Project Staging Server', 'deposit' => $deposit, 'baseUri' => $this->router->generate('home', array(), UrlGeneratorInterface::ABSOLUTE_URL), 'plnJournalTitle' => $this->plnJournalTitle));
     if ($this->saveDepositXml) {
         $atomPath = $this->filePaths->getStagingDir($deposit->getJournal()) . '/' . $deposit->getDepositUuid() . '.xml';
         file_put_contents($atomPath, $xml);
     }
     try {
         $client = $this->getClient();
         $request = $client->createRequest('POST', $this->colIri);
         $request->setBody(Stream::factory($xml));
         $response = $client->send($request);
         $responseXml = new SimpleXMLElement($response->getBody());
     } catch (RequestException $e) {
         $this->logger->critical($e->getMessage());
         if ($e->hasResponse()) {
             $xml = $e->getResponse()->xml();
             $xml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
             $xml->registerXPathNamespace('sword', 'http://purl.org/net/sword/');
             $this->logger->critical('Summary: ' . (string) $xml->xpath('//atom:summary')[0]);
             $this->logger->warning('Detail: ' . (string) $xml->xpath('//sword:verboseDescription')[0]);
         }
         return false;
     } catch (Exception $e) {
         $this->logger->critical("Error parsing deposit response from server: {$e->getMessage()}");
         return false;
     }
     $deposit->setDepositReceipt($response->getHeader('Location'));
     $deposit->setDepositDate(new DateTime());
     // TODO should I do something wtih responseXML here?
     $this->namespaces->registerNamespaces($responseXml);
     return true;
 }
コード例 #27
0
 /**
  * {@inheritdoc}
  */
 public function render($name, array $parameters = array())
 {
     $e = $this->stopwatch->start(array('server' => 'localhost', 'group' => 'twig::render', 'twig_template' => (string) $name));
     $ret = parent::render($name, $parameters);
     $e->stop();
     return $ret;
 }
コード例 #28
0
 /**
  * @DI\Observe("widget_badge_usage_configuration")
  *
  * @param ConfigureWidgetEvent $event
  */
 public function onConfig(ConfigureWidgetEvent $event)
 {
     $badgeWidgetConfig = $this->badgeWidgetManager->getBadgeUsageConfigForInstance($event->getInstance());
     $this->badgeUsageForm->setData($badgeWidgetConfig);
     $content = $this->templating->render('IcapBadgeBundle:Widget:badge_usage_config.html.twig', ['form' => $this->badgeUsageForm->createView(), 'instance' => $event->getInstance()]);
     $event->setContent($content);
 }
 /**
  * Constructor.
  *
  * @param \Twig_Environment           $environment  A \Twig_Environment instance
  * @param TemplateNameParserInterface $parser       A TemplateNameParserInterface instance
  * @param FileLocatorInterface        $locator      A FileLocatorInterface instance
  * @param RequestStack                $requestStack A RequestStack instance
  * @param array                       $devices
  * @param string                      $deviceTypeField
  */
 public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator, RequestStack $requestStack, array $devices, $deviceTypeField)
 {
     parent::__construct($environment, $parser, $locator);
     $this->request = $requestStack->getMasterRequest();
     $this->devices = $devices;
     $this->deviceTypeField = $deviceTypeField;
 }
コード例 #30
0
 /**
  * Generate config file
  *
  * @param $fileName string file in app/supervisor dir
  * @param $vars array array(name,command,[directory,numprocs], options => [key => value,...])
  */
 public function genProgrammConf($fileName, $vars)
 {
     $template = 'SupervisordBundle:conf:program.conf.twig';
     $filePath = $this->appDir . '/supervisor/' . $fileName . '.conf';
     // Handle directory
     if (!isset($vars['directory'])) {
         $vars['directory'] = $this->appDir;
     }
     // If file exist delete it
     if (file_exists($filePath)) {
         unlink($filePath);
     }
     // Generate content
     $content = $this->templating->render($template, $vars);
     // Write content
     file_put_contents($filePath, $content);
 }