how to use in_array in ejs template - node.js

How to use in_array or similar in inside an ejs template?
This is how I use it on php:
<?php
$cur_repository_id = array();
foreach($dbrepos as $row){
$shared_ids = $row['shared_ids'];
if(in_array($user_id, $shared_ids)){
$selected = "selected";
$cur_repository_id[] = $row['rep_id'];
}else{
$selected = "";
}
?>
<option value="<?php echo $row['rep_id'];?>" <?php echo $selected;?>><?php echo $row['namespace'];?></option>
<?php
}
?>

Equivalent of in_array in javascript is includes
So if for example you want to pass an array from Node.js to ejs file, you can do something like that:
res.render('index', {numbers : [1, 23, 44]});
And then inside ejs you can use the method includes, for example:
<body>
<% if(numbers.includes(44)){ %>
<h1>44 exists</h1>
<% } else{ %>
<h1>44 not exists</h1>
<% } %>
</body>
Also you can use method indexOf, which return the index of given value in an array.

Related

Is there a way to Include / Render a variable in EJS?

Is there a way to have the contents of an include come from a variable instead of a from a file?
I need to get the contents of the include from a database instead of a file, I would like to do something like this:
Contents of example.ejs:
<h1>Example EJS template<h1>
<p><%- include(data.includeCode) %><p>
Nodejs / Express with EJS code:
let includeCode = `<% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %>`
let ejsdata = {...{includeCode: includeCode}, ...{dSwitch: 1}};
res.render("example.ejs",{data:ejsdata});
What I would like to see is the following output:
<h1>Example EJS template</h1>
<p> 1 detected </p>
I tried using <%- data.includeCode %> but that outputs as
<h1>Example EJS template</h1>
<p> <% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %> </p>
The solution is to call ejs.render from the ejs template:
Contents of example.ejs:
<h1>Example EJS template<h1>
<p><%- ejs.render(data.includeCode,{data:data}) %><p>
NodeJS / Express with EJS code:
import ejs from "ejs";
globalThis.ejs = ejs; // make sure ejs is available in the global context
let includeCode = `<% if (data.dSwitch === 1) { %> 1 detected <% } else { %> Something else <% } %>`
let ejsdata = {...{includeCode: includeCode}, ...{dSwitch: 1}};
res.render("example.ejs",{data:ejsdata});
Resulting Output:
<h1>Example EJS template</h1>
<p> 1 detected </p>

Custom search using doctrine and symfony2

I want to create a searchController, that searches the db for whatever keywords the user enters into a textbox. I have looked at this article and this and many more.
This is what I have so far:
public function searchAction(Request $request) {
if ($request->getMEthod() == 'GET') {
$title = $request->get('Search_term');
//echo "<div class=\"searchText\">Search Results</div><hr/>";
$em = $this->getDoctrine()->getManager();
$Search_terms = explode(' ', $title); //splits search terms at spaces
$query = "SELECT * FROM Entity/Adverts WHERE ";
foreach ($Search_terms as $each) {
// echo $each."<br/>";
$i = 0;
$i++;
if ($i == 1)
$query .= "Adv_title LIKE '%$each%' ";
else
$query .= "OR Adv_title LIKE '%$each%' ";
}
$query = $em->createQuery($query);
$numRow = $query->count();
if ($numRow > 0) {
while ($query->fetch()) {
$repository = $em->getRepository('YCRYcrBundle:Adverts')->findBy(array(
'advTitle' => $title
));
/* echo "<h2><a href='#'> $title</a> </h2>";
echo "$desc <br /> <br />";
echo"<a href='/201308/View/YCR/index.php' class='link-button right'><span>Apply</span></a>"; */
}
}
/* else
echo "none found for \"<b>$SearchTerm </b>\"</br>Check spelling"; */
}
return $this->render('YCRYcrBundle:Search:search.html.twig', array('title' => $title->getAdvTitle()));
}
What is missing from this code to make it work, and or what is wrong?
Edit:
sorry of I was unclear. I am getting the following error:
FatalErrorException: Error: Call to undefined method Doctrine\ORM\Query::count() in C:\wamp\www\201308\src\YCR\YcrBundle\Controller\SearchController.php line 28
and do not know what is wrong as I am new to Symfony and doctrine.
This is what I have in my search.html.twig:
{% extends "YCRYcrBundle::layout.html.twig" %}
{% block content %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>YCR Job Search</title>
<link href="stylesheets/style.css" rel="stylesheet" type="text/css" />
<link href="stylesheets/colour.css" rel="stylesheet" type="text/css" />
</head>
<body onload="b = setInterval('clear()', 0);">
<div class="topDiv">
<div style="float: left;">
<img src="/201308/View/images/ycr.jpg" alt="ycr"></div>
<br/>
<!--<H2>Search for a Job</H2>-->
<div class="searchform">
<form id="formsearch" name="p" method="get" action="index.php">
<span>
<input name="Search_term" class="editbox_search" id="editbox_search" maxlength="80" value="<?php $this; ?>" type="text" />
</span>
<input type="image" name="button_search" src="images/search.gif" class="button_search" alt="" />
</form>
<br/>
<div id="search_results">
</div>
</div>
<!-- </div>-->
<script type="text/javascript" src="http://code.jquery.com/jquery- 1.7.2.min.js"></script><!--javascript jquery library-->
<script type="text/javascript" src="../View/scripts/Script.js"></script>
{% endblock %}
When the user searches, for example programmer, to display like this:
-Programmer
-a summary of the description of what a programmer entails
-a button/link that reads: read more, that takes me to a page with full description
You are pretty far off the mark. Query has no count function, that's a querybuilder function. You may write raw sql, but you are better served learning querybuilder : http://docs.doctrine-project.org/en/latest/reference/query-builder.html. Remember, doctrine is designed to give you a list of entities, that you pass to the twig to do stuff with.
Also, your twig won't do much, see the basics of usage in the very crude twig I've included. use {{entity.method}} or {{entity.field}} to get the various display properties of each entity. Use a twig foreach to loop through them all. Take a look at my example in your context, and then go read the twig documents to fill in the gaps. http://twig.sensiolabs.org/documentation
The Controller
public function searchAction(Request $request) {
if ($request->getMethod() == 'GET') {
$title = $request->get('Search_term');
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository('YCRYcrBundle:Adverts')
->createQueryBuilder('a');
$searches= explode(' ', $title);
foreach ($searches as $sk => $sv) {
$cqb[]=$qb->expr()->like("CONCAT($sv, '')", "'%$sv%'");
}
$qb->andWhere(call_user_func_array(array($qb->expr(),"orx"),$cqb));
$adverts = $qb->getResult();
}
return $this->render('YCRYcrBundle:Search:search.html.twig'
, array('adverts' => $adverts));
}
And a twig file
{# Your other stuff #}
{% for advert in adverts %}
{{advert.getId}}
{# call the various method and fields for your display#}
{% endfor %}
you need to execute the query (with execute ) or you wont get an array. and you should be using the query builder instead DQL string concatenation. Read the doctrine doc on basic doctrine usage , the entity namespace seems to be incorrect too.
i quote you :
$query = $em->createQuery($query);
$numRow = $query->count();
should be at least :
$query = $em->createQuery($query);
$numRow = count($query->execute())
edit : not sure wether you would be getting an array or an ArrayCollection , check if the count fonction works on the ArrayCollection.

How to get all locals in Express view

I am trying to figure out a way to get access to all the app.locals in the views. In my app.js I have
app.locals.title = "Title"
app.locals.page = "Page 1"
This is good, and in the views, I can access each with
<%= title %>
<%= page %>
However, is there a way (without doing something like app.locals.xyz.title) to get all the locals in the view so I can do something like this:
<% for(var i=0; i < locals.length; i ++ ){ %>
<li><%= locals[i] %></li>
<% } %>
You have to explitly pass it:
res.locals.locals = res.locals;
Then in the view:
<%= locals %>

Does EJS handle array.map(callback)?

I am passing an array of objects to an EJS template, which I would like to map into links using the regular .map() method of arrays. But for reasons I can't figure out, the callback I'm passing to map() doesn't work within EJS the way I'd expect, and I'm getting empty results.
My data is an array of objects, each with a "section" and a "name" key. This array is passed as "entries" to the template:
siteHeaders = [ { section: "home", name: "Home"},
{ section: "about", name: "About Me"},
... plus few more ]
The template looks like this, and I have it in a local variable called (surprise) template:
<% entries = entries.map(function(elem) { -%>
<% return -%>
<a href="/<%= elem.section %>">
<%= elem.name %>
</a>
<% } ) -%>
<p><%- entries.join(" | ") %></p>
The result of this template, when I call require('ejs').render(template, {entries: siteHeaders}) is:
<p> | | | | </p>
What I don't get is why this doesn't work in an EJS template, when the corresponding map call works just fine in REPL:
> siteHeaders.map(function(e){ return '' + e.name + '' })
[ 'Home',
'About Me',
'Portfolio',
'Blog',
'Contact' ]
>
Any clues?
This code should work:
<% entries = entries.map(function(elem) {
return '' + elem.name + '';
}) -%>
<p><%- entries.join(" | ") %></p>
You can't use simple html inside of functions. It's possible only in loops and conditions.
It's not as clean as join(' | '), but if you don't want to concatenate, you can do this:
<% entries.forEach(function(entry, i, entries){ %>
<%= entry.name %>
<%= i == entries.length-1 ? ' | ' : '' %>
<% } %>
I didn't manage to use map in EJS, but I found a way that at least for me is easy too
<ul>
<% for (item of toDoList) { %>
<li> <%= item %> </li>
<% } %>
</ul>

How to print a variable directly using EJS template engine?

I'm using Node.js with Express web framework (and EJS template engine).
When I have to print a variable I do something like:
<% if (value) { %>
<%= value %>
<% } %>
Can I do the same thing without open others brackets ? Like:
<% if (value) { PRINT VALUE } %>
Is this possible? How to print the variable?
I'm amazed to find that apparrently you can't do it, like in PHP:
<?php if ($value) : ?>
<?php echo $value; ?>
<?php endif; ?>
However a slightly better solution may be to do
<%= (value) ? value : '' %>
I say this assuming that the condition may occasionally be more complex, i.e.
<%= (str.length > 100) ? truncate(str) : str; %>
Which is much nicer than
<% if (str.length > 100) { %>
<%= truncate(str) %>
<% } %>
even if it is a slightly contrived example.
I'd love to be shown a direct command to do it, as per your original question.
There is now an outputFunctionName parameter that you can use. According to the documentation:
outputFunctionName Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags.
<% console.log(posts) %>
NB: Make sure you define your variable in any other file you have eg app.js file...
let posts = [];
app.get("/", (req, res) => {
res.render("home", {
posts: posts
});
});

Resources