Apache Velocity: hashtable? - velocity

The Velocity user guide mentions a "Hashtable". However there's no mentioning how to create one in this language.
So if you could show how to do this
-- so that I could write smth. like
#foreach( $key in $foo.keySet() )
<li>Key: $key -> Value: $foo.get($key)</li>
#end
-- I'd greatly appreciate your help.
Thanks in advance!
// PS: my original problem is : Mechanical Turk / Cmd line tools / Qualification / #set and #foreach in xml
So please understand that I am not interested in learning Velocity -- I only need one quick hack if possible. Thanks.

In Velocity you would use the #set directive to create a map. To relate it to your example you might do something like:
#set($foo = {
"NEWS": "http://news.bbc.com",
"SEARCH": "http://google.com"
})
Then your foreach example above will do exactly what you need.

Related

Can this list be sorted by date in Velocity?

I've found this code for getting articles by tag and display them as a list with links in xWiki, but I want it sorted by date.
Has anyone a suggestion for me?
{{velocity}}
#set ($list = $xwiki.tag.getDocumentsWithTag('myTag'))
#foreach($reference in $list)
#set ($document = $xwiki.getDocument($reference))
#set ($label = $document.getTitle())
[[$label>>$reference]]
#end
{{/velocity}}
Thanks in advance!
Sorting in velocity can hit one of 2 performance penalties:
Actually sorting in velocity, either with a sorting algorithm -> unnecesarrily compicated
Loading all the document results into memory (a collection) and
sorting that collection with the sort/collection tool -> you risk quickly running out of memory if the result is larger than you expected.
The easiest alternative, given that there is XWiki running behind it, would be to do an XWQL query for the XWiki.TagClass objects stored inside the documents and do the sorting at the database level. At this point, in velocity, you only need to display the results:
{{velocity}}
#foreach ($docStringRef in $services.query.xwql("from doc.object(XWiki.TagClass) tagsObj where 'conference' member of tagsObj.tags order by doc.creationDate DESC").setLimit(10).execute())
#set ($document = $xwiki.getDocument($docStringRef))
[[$document.title>>$docStringRef]]
#end
{{/velocity}}
For future use/reference, the list of available Velocity tools in XWiki might also be useful https://extensions.xwiki.org/xwiki/bin/view/Extension/Velocity%20Module#HVelocityTools since they can help with common operations, including sorting (that I mentioned at point 2. above)

Is there an alternative to round a number in Apache Velocity without using MathTools?

I need to round a quantity in Apache Velocity, but it is supposed I'm not allow to change pom.xml at work, so, is there an alternative to skip MathTools?
I tried this example:
#set($String = "abc")
$String.format("%.2f", $val)
but it's not working,
Any help will be thankful.
Didn't you forget an hash sign before set? The following is working for me:
#set($val=0.1294)
#set($String = "abc")
$String.format("%.2f", $val)
Output:
0.13

can there be a tooltip with data from the database

I need to know can there be a tooltip populated with data from database to be displayed in the tooltip.
something like the tooltip should contain
name stauts
abc active
xyz active
pqr active
name and status are retrived from db
I need this tooltip onmouseover, am using CJSON decoded to render the content
i did go google but hardly did find that i would throughly understand and implement.
can anyone out there has any ideas for what am looking.
There is a extension named yii-bootstrap, which described clearly here.
For using tooltip easily in this extension, just look here.
I use cluetip for this. Its not related to Yii but will give you some idea :
JS
function renderInfoTips(opts){
var elements=$('#'+opts.form).get(0).elements;
for(i=0; i<opts.tips.length;i++){
$(elements[opts.tips[i].field]).parent().prepend(opts.tips[i].tip);
}
var clue_opts={arrows:true,splitTitle: '|',closePosition: 'title',sticky:true,dropShadow:false,mouseOutClose:true,
onShow:function(ct, ci){
if(!$.browser.webkit) $(ct).css('top',$(ct).position().top- 30+'px');
}
}
$('#'+opts.form).find(".infotip").cluetip(clue_opts);
}
PHP
function setInfoTipsJavascript($form_id,infotips){
if (count($this->infotips) <1 ) return '';
//get all tip names
$names_csv=join(',',array_keys(infotips));
//get tips details from db
$query="select name, description from infotips where FIND_IN_SET(name ,'$names_csv')";
//run the query, in Yii you have to use InfoTipsModel , I have skipped that portion
//$infotipS , lets say this is query object
$tips=array();
while($tip=$infotipS->Assoc()){
$this->infotips[$tip['name']]['tip']="<a href='javascript:void(0)' class='infotip' title='|{$tip['description']}'> </a>";
$tips[]=$this->infotips[$tip['name']];
}
$tips=json_encode($tips);
$script="\nrenderInfoTips({\"form\":'{$form_id}', \"tips\":{$tips}});\n\n";
echo $script;
}
I am sharing this hoping this will give u some idea. Its obvious you have to : create infotips table, a model for that, and create a widget etc to fetch infotips related to your form fields . As someone suggested, if you are using Bootstrap, you have better way to do that.

Mechanical Turk / Cmd line tools / Qualification / #set and #foreach in xml

In the Amazon Mechanical Turk command line tools (I am using version: aws-mturk-clt-1.3.0), in one of the samples (site_filter_qual: "Website Filtering Qualification", file site_filter_qual.question), there is code that looks something like this:
#set( $urls = [ "http://news.bbc.co.uk/", http://..., ...])
#foreach ( $url in $urls )
...
I am wondering :
a) What is the language used here (it's
not Perl and not PHP, right?);
b)
Where (on Amazon site or elsewhere) I
could read about these constructs;
c)
How to implement tuples (pairs), e.g.
// in Python:
>> data = [("http://news.bbc.com", "NEWS"), ("http://google.com", "SEARCH"), ...]
>> for (url, category) in data:
>> ....
-- or something similar?
Thanks in advance!
It's a Velocity template (part of the Apache project). The good news is that it's a reasonably flexible language that you can manipulate. The better news is that you can (since I believe all the CLT and SDK code is open) actually create new constructs to override or expand on anything that's not part of Velocity out-of-the-box.
To answer your questions directly:
a) Velocity
b) http://velocity.apache.org/
c) You can use two separate arrays. Not pretty, I realize, but it'll work.

drupal bootstrap script: how to get list of all nodes of type x?

I create a custom import and export, at the moment as an external script (via bootstrap), i plan to create a module in a more generic fashion lateron.
I am building a frontend for nagios and for our host management and nagios configuration btw. Maybe it might become useful for other environments (networkmanagement)
Now i need to know how to get list of all nodes of type x?
I want to avoid direct SQL.
A suggestion i got was to make an rss and parse it
but i acess the drupal db a dozen times to extract various nodes, so it feels strange to do a web request for one thing
So what i am looking for as newbie drupal dev is just a pointer to basic search module api for this task
TIA
florian
Why do you want to avoid using SQL?
If you want to get info about what's in your db, like all the nodes of type x, the only way to get it, is through a SQL query, unless you have the data extracted already.
A query like
db_query("SELECT title, nid FROM {node} WHERE type = 'x';");
shouldn't be the thing that ruins your performance.
Edit:
The link you provided is a from Drupal 7, so you have to be be careful reading this. The reason is that in Drupal 7 it is not only possible to use db_query which basically is wrapper for the php functions mysql_query, pg_query. It's a bit different and using it, you wont have to use db_specific code. Anyways new in Drupal 7 is something that is a bit like an ORM. I haven't read about it in detail, but the idea is that you can build a query using commands on an object. This is probably what you are after. However, Drupal 7 is not ready at all for production sites. There are still a lot of critical issues and security issues. So this wont be a possibility for quite some time.
Edit 2:
If you want to get the node title and body, this is what you should do:
$type = 'x';
$query = db_query("SELECT r.nid, r.title, r.body FROM {node} AS n
LEFT JOIN {node_revisions} AS r ON r.nid = n.nid
WHERE type = '%s';", array($type));
$nodes = array();
while ($node = db_fetch_object($query)) {
$nodes[$node->nid] = $node;
}
You can use db_fetch_array instead of db_fetch_object` if you want to extract arrays instead of objects from the db.
This is a pretty old question, but for anyone coming across this page now, in Drupal 7.x best practise is to use dynamic queries.
So if you wanted to select all the nodes of type x, you could do the following:
$articles = db_select('node')
->fields('node', array('nid', 'title'))
->condition('type', 'x', '=')
->execute()
->fetchAllKeyed();
The $articles variable should then be an array of all x type nodes, keyed by nid with the arrays corresponding value set to the node title. Hope that can help.
Views is generally how you create database queries without writing them in Drupal, but this query is so simple I'm not sure it's worth the overhead of learning views, barely 5 lines after you've bootstrapped Drupal:
$nodes = array();
$results = db_query("SELECT nid FROM {node} WHERE type = '%s'", $type);
while ($result = db_fetch_object($result)) {
$nodes[] = node_load($result->nid);
}
Gotta use SQL do to this.
http://api.drupal.org/api/function/node_get_types/6
Node counts =
$node_types = node_get_types();
$type_count = array();
foreach ($node_types as $type) {
$result = db_fetch_object(db_query('SELECT count(nid) AS node_count FROM {node} WHERE type = "%s"'), $type);
$type_count[$type] = $result['count(nid)'];
}
print_r($type_count);
Nodes and their type:
$node_types = node_get_types();
$nodes = array();
foreach ($node_types as $type) {
$result = db_query('SELECT nid, title FROM {node} WHERE type = "%s"'), $type);
while ($node = db_fetch_object($result)) {
$nodes[] = array('Type' => $type, 'Title' => $node->title);
}
}
print_r($nodes);
Something like that. I am eating lunch so I didn't test that but I have done this before so it should work. Drupal 6.
The migrate module may be of interest to you. It also supports drush so you can script things fairly easily.