Iterating over parameters

Iterating over parameters

by Paul Powell -
Number of replies: 1

I was having an issue iterating over a parameter set. I wanted to do this to make multi-line parameters more straightforward to input (rather than using \n). After some head-scratching, I found using the dump() method that the parameter was being passed as a StdObj rather than as an array.

I put a hack into the render function in php.twig like so:

 public static function render($s, $student, $parameters=array(), $isstrict=false) {
        $twig = qtype_coderunner_twig::get_twig_environment($isstrict);
        $parameters['STUDENT'] = new qtype_coderunner_student($student);
        if (array_key_exists('__twigprefix__', $parameters)) {
            $prefix = $parameters['__twigprefix__'];
            $s = $prefix . $s;
        $template = $twig->createTemplate($s);
        $parameters=json_decode($parameters, true);
        $renderedstring = $template->render($parameters);
        return $renderedstring;

The hack encodes to json and decodes back (original idea from here) which then means everything in the parameter string is converted to an array. This means that it is Traversable in Twig and thus can be iterated over. If I add the array extension to Twig, then I should also be able to shuffle the array. Presumably there is something somewhere not returning an array, but I am not that into the code base at the moment.

This then gets me server-side randomising of program lines for my Parson's Problem project.

Is this worth looking at in the main code?



In reply to Paul Powell

Re: Iterating over parameters

by Richard Lobb -

We have briefly discussed this in the Parsons Problem thread. But if we're to continue the discussion of this particular issue, I think we should do so in this thread.

Just to provide a context for anyone else landing here, my posting to the Parson's problem thread was:

Another recent poster (see this thread) also wanted to have JSON objects passed in to Twig as associative arrays rather than as objects. I can achieve that simply by changing one line of code - a call to json_decode - passing in a parameter to force associative arrays rather than objects. As I said in that thread: "... I'm sorry, but I'm not prepared to make that change, as I don't know what other consequences there might be. You're the first person who has ever drawn my attention to this and I feel the risks are just too great." But with a second person asking I am prepared to rethink.

It's possible that I could break existing question types by making that change, for example if someone were using the Twig attribute function to extract attributes from the object. But more fundamentally it seems to me that JSON objects should get converted to Twig object whereas JSON arrays should get converted to Twig arrays. Iterating over the attributes of an object is sometimes convenient but never pretty. If you want to iterate over something, shouldn't it be a list?!