Procedimientos de ExpressionScript
From LimeSurvey Manual
Resumen de lo explicado anteriormente
Si has seguido hasta ahora la estructura del manual de LimeSurvey, significa que ya conoces la Terminología de LimeSurvey. A continuación, cubrimos expresiones y variables para aprender cómo mejorar nuestras encuestas. En la siguiente parte, pasamos a los tipos y significados de resaltado de sintaxis para aprender cómo corregir errores de sintaxis.
Con estas nociones básicas cubiertas, podríamos avanzar hacia ejemplos y explicar cómo funcionan las expresiones dentro de LimeSurvey.
Resaltado de sintaxis
Las siguientes capturas de pantalla brindan ejemplos, pero no muestran los valores de la información sobre herramientas. Una información sobre herramientas es un cuadro informativo que se muestra cada vez que pasa el mouse sobre cualquier palabra en negrita.
Gracias a este resaltado de sintaxis, es muy fácil componer expresiones correctas, incluso aquellas que son complicadas. Aunque el equipo de LimeSurvey planea intentar crear una GUI de Expression Builder, puede utilizar el resaltado de sintaxis existente para identificar y corregir rápidamente errores tipográficos. También puede utilizar la información sobre herramientas para validar la precisión de sus expresiones (por ejemplo, confirmar que ha seleccionado las variables deseadas).
En cada uno de los ejemplos, hay tres columnas:
- Fuente: este es el texto sin formato que ingresaría en el campo de preguntas de LimeSurvey.N!#Pretty Print: ¡este es el equivalente resaltado en sintaxis de lo que ingresó! N!#*Tenga en cuenta que las expresiones se muestran con un fondo tostado, pero no rodeadas por llaves en este resaltado.
- Dado que EM admite la sustitución recursiva, mostrar llaves en el resaltado provocaría errores de sintaxis.N!#Resultado - ¡Esta es la salida generada cuando EM procesa la fuente
- Todo lo que se puede sustituir correctamente es
- Las expresiones con errores se muestran en línea, con resaltado de sintaxis. Los errores están rodeados por un cuadro con líneas rojas.
Sintaxis adecuada
Puede encontrar a continuación ejemplos de sintaxis adecuada:
- Valores: muestra que las variables conocidas están codificadas por colores según estén configuradas en la página actual. INSERTANTES de estilo antiguo:xxxx obtiene su propio estilo de codificación de colores.
- Atributos de preguntas: ¡muestra que la notación de puntos puede acceder a algunas propiedades de las preguntas
- Matemáticas: ¡muestra que se admiten cálculos básicos y complejos
- Procesamiento de texto: muestra algunas de las funciones de procesamiento de texto disponibles
- Dates: muestra dos de las funciones disponibles relacionadas con fechas
- Conditional: muestra el uso de la función if(). Las opciones se pueden anidar.
- Párrafo personalizado: puede personalizar completamente un informe basado en valores anteriores
- Procesos EM dentro de cadenas: muestra que puede hacer sustituciones dentro de cadenas. Este ejemplo genera un nombre de imagen personalizado.
- EM no procesa llaves como estas: muestra que si se escapan las llaves, o hay un espacio en blanco entre la expresión y las llaves, ES ignora la expresión.

Sintaxis de EM que contiene errores
A continuación se muestran ejemplos de errores comunes al escribir expresiones ES. Tenga en cuenta que la información sobre herramientas proporciona información adicional.
- Javascript en línea que olvidó agregar espacios después de la llave
- Dado que "document.write" aparece justo después de una llave, EM piensa que es una expresión y red- cuadros "documento" y "escribir" ya que son variables y funciones no definidas, respectivamente
- Variables, funciones y operadores desconocidos/mal escritos
- Aquí olvidamos que estamos usando el nombre de variable "género" en lugar de " sexo", pero EM detecta ese error. También encuadra en rojo '++', ya que no es un operador admitido.
- Advierte si se usa = en lugar de eq, o realiza asignaciones de valores
- Tenga en cuenta que '=" y '+=' están en texto rojo en lugar de negro. Si pasa el mouse sobre ellos, verá advertencias de que está asignando un valor.
- Número incorrecto de argumentos para funciones
- if() toma 3 argumentos, pero se le han dado 4, por lo que al pasar el cursor sobre el "si" encuadrado en rojo se explicará el error y se mostrará la sintaxis admitida. N!#*sum() toma un número ilimitado de argumentos, pero teníamos una coma al final antes del paréntesis de cierre, ¡así que está encuadrado en rojo! N!#Paréntesis no coincidentes
- Este es uno de los errores más comunes al escribir expresiones.
- Esto muestra dos ejemplos de paréntesis de cierre faltantes y un ejemplo de tener demasiados paréntesis de cierre.
#¡Sintaxis no compatible
- Si utiliza un operador o puntuación que ES no admite, lo marcará en un recuadro rojo.
- Asignaciones no válidas
- Algunas variables son de lectura y escritura y se pueden cambiar sus valores. Otras son de sólo lectura.
- Si intenta cambiar el valor de una variable de sólo lectura, no podrá. EM marcará el intento en un cuadro rojo.
- Si intenta asignar un valor a una ecuación o una cadena, también obtendrá un error

"Ejemplos en vivo" de resaltado de sintaxis con información sobre herramientas activa
!¡NORTE!!¡NORTE!Fuente | Bonita impresión | Resultado |
---|---|---|
A continuación se muestra un ejemplo de sintaxis OK con información sobre herramientas. Hola {if(gender=='M','Mr.','Mrs.')} {apellido}, ahora es {fecha('g:i a',time())}. ¿Sabes dónde están tus {sum(numPets,numKids)} hijos y mascotas? | A continuación se muestra un ejemplo de sintaxis OK con información sobre herramientas. Hola , si ( género == 'M' , 'Mr.' , 'Mrs.' ) apellido , ahora es fecha ( 'g:i a' , hora ()) . ¿Sabe dónde están sus hijos y mascotas suma ( numPets , numKids ) ? | A continuación se muestra un ejemplo de sintaxis OK con información sobre herramientas. Hola Sr. Smith , ahora son las 6:07 am. ¿Sabes dónde están tus 3 hijos y tus mascotas? |
Aquí hay errores comunes para que pueda ver la información sobre herramientas. Variables utilizadas antes de declararse: {notSetYet} Función desconocida: {iff(numPets>numKids,1,2)} Variable desconocida: {suma(edad,num_pets,numKids)} # parámetros incorrectos: {sprintf()},{if(1,2)},{date()} Asignar variables de solo lectura:{TOKEN:ATTRIBUTE_1+=10},{name='Sally'} Paréntesis desequilibrados: {pow(3,4},{(pow(3,4)},{pow(3,4))} | Aquí hay errores comunes para que pueda ver la información sobre herramientas. Variables utilizadas antes de ser declaradas: notSetYet Función desconocida: iff ( numPets > numKids ,1,2) Variable desconocida: suma ( edad , num_pets , numKids ) # parámetros incorrectos: sprintf () , if (1,2) , fecha () Asignar variables de solo lectura: TOKEN:ATTRIBUTE_1 += 10 , nombre = 'Sally' Paréntesis desequilibrados: pow (3,4 , (pow (3,4) , pow (3,4) ) | Aquí hay errores comunes para que pueda ver la información sobre herramientas. Variables utilizadas antes de ser declaradas: notSetYet Función desconocida: iff ( numPets > numKids ,1,2) Variable desconocida: suma ( edad , num_pets , numKids ) # parámetros incorrectos: sprintf () , if (1,2) , fecha () Asignar variables de solo lectura: TOKEN:ATTRIBUTE_1 += 10 , nombre = 'Sally' Paréntesis desequilibrados: pow (3,4 , (pow (3,4) , pow (3,4) ) |
A continuación se muestra parte de la sintaxis no admitida. No hay soporte para '++', '--', '%',';': {min(++age, --age,age % 2);} Ni '|', '&', '^': {(suma(2 | 3,3 y 4,5 ^ 6)}} Ni matrices: {nombre[2], nombre['mío']} | A continuación se muestra parte de la sintaxis no admitida. No hay soporte para '++', '--', '%',';': min ( ++ edad , -- edad , edad % 2) ; Ni '|', '&', '^': ( suma (2 | 3,3 y 4,5 ^ 6) } Ni matrices: nombre [ 2 ] , nombre [ 'mío' ] | A continuación se muestra parte de la sintaxis no admitida. No hay soporte para '++', '--', '%',';': min ( ++ edad , -- edad , edad % 2) ; Ni '|', '&', '^': ( suma (2 | 3,3 y 4,5 ^ 6) } Ni matrices: nombre [ 2 ] , nombre [ 'mío' ] |
Ejemplos de adaptación (p. ej., extensión de {INSERTANS:xxx})
"Estimado {Señor}/{Señora} Smith..."
Utilice la función if() para elegir condicionalmente si se muestra 'Mr.' o 'Señora'.
The syntax is if(test,do_if_true,do_if_false).
# | Code | Question | Type |
1 | gender | What is your gender? | Gender |
2 | example1 | Dear {if(gender=='M','Mr.','Mrs.')} Smith, ... | Long free text |

As it can be observed below, "Mr" and "Mrs" are tailored to what the respondent selects as answer to question "gender".


"Dear {Mr}/{Mrs} Smith..." in invitation email
You can use the example above in the invitation email using attributes from the token table. Use the if() function to choose whether 'Mr.' or 'Mrs.' should be used in the email.
The syntax is "if(test,do_if_true,do_if_false)".
# | attribute | value |
1 | Last name | Smith |
2 | Email address | test@test.com |
3 | ATTRIBUTE_2 | M |
Text in invitation email:
Dear {if(ATTRIBUTE_2=='M','Mr','Mrs')} {LASTNAME},
you have been invited to participate in a survey:
https:/...

email View:

Calculation / Assessment Examples
Calculate assessment values at runtime and store the results in the survey data
This example uses all of EM's features, including Relevance, Tailoring, and the Equation question type.
It also shows that all of them are JavaScript-enabled, so if you have these features on a page, it will dynamically change as people set and change their answers.
# | Code | Question | Type | Relevance |
1 | numKids | How many children do you have? | Numerical input | 1 |
2 | kid1 | How old is your first child? | Numerical input | numKids >= 1 |
3 | kid2 | How old is your second child? | Numerical input | numKids >= 2 |
4 | kid3 | How old is your third child? | Numerical input | numKids >= 3 |
5 | kid4 | How old is your fourth child? | Numerical input | numKids >= 4 |
6 | sumKidAges | {sum(kid1.NAOK,kid2.NAOK,kid3.NAOK,kid4.NAOK)} | Equation | 1 |
7 | kidSummary | You said that you have {numKids}. {if(numKids==1,'child','children')}. {if(numKids>1,implode(' ','The sum of ages of your first ',min(numKids,4),' kids is ',sumKidAges,'.'),' ')} | Text display | 1 |
To download this example, please click on the following link: Assessments_survey_example.
You may find below screenshots of representative questions. As you can see, EM syntax-highlights all fields that might contain tailoring. Here, you see examples of syntax-highlighting Relevance, the Equation question type, and substitutions within a question. You can also use substitutions within Help, Group header display, Welcome message, and End message.
In the next example, since the relevance is {numKids >= 2), the question will only be visible if the respondent reports that she has at least two children.

Below, you may observe that each variable has the .NAOK suffix attached to it. This is because of how EM supports cascading relevance. If you did not have .NAOK, then the sum would only be computed if the person said she has 4 children (e.g., if all of the variables are relevant). The usage of .NAOK means that we want to compute the sum even if all or some of the variables are irrelevant (e.g., "Not Applicable" (NA) is alright (OK)).
However, the .NAOK attribute only affects whether variables are passed into EM. If the respondent initially says she has 3 children, and enters ages for each, then changes her mind and says she has 2, we don't want to see the sum of the 3 entered values - since the third child is "not applicable" in our case anymore:

Each separate Expression is color coded with a tan background. As you can see, there are three separate Expressions here. The last one contains a message that is conditionally shown only if the person has more than one child.

Now, here are screenshots of the survey in action.
When you first visit the page, you see this. Note that is says "You have 0 children" instead of "You have 0 child".

If I change the value for number of children to 1, the display instantly changes to this, even though it is on the same page:

Now notice that the grammar is correct: "You have 1 child".
Now I change the value for number of children to 3, and the display instantly changes to this.
Notice that you now see the conditional message at the bottom: "The sum of ages of your first 3 kids is 0.".
Now I'll enter ages for my imaginary children, and I get this display, summing up their ages:

Again, the score and display updates instantly as I enter the values, so you can use this to show a running total of an Assessment Score.
Now, I change the value for the number of children to 2. The display has changed to this:

Notice that although I had entered a value of 5.5 for the third child, the report now only sums the values of my first 2 children.
The reason for this is that the 3rd value is now irrelevant, and irrelevant values are actively ignored by EM.
If I were to change the number of kids back to 3, I would see the value of 5.5 I entered again. So, I don't lose any information I enter on the page.
However, if I navigate to the Next or Previous page, all irrelevant values will be NULLed out in the session and in the database. So, if I were to keep the value at 2, go to the next page, and then come back and state that I actually have 3 kids, I would no longer see the age of 5.5.
Enter data and see a dynamically changing report of what was entered on the same page
This example presents the Tailoring process within LimeSurvey.
To download this example, click on the following link: Dynamic changes survey example.
Here is what the page looks like initially. You only see the question asking what city you live in:

Once you start to enter an answer, the tailoring process is also starting:

As you enter answers, the table at the bottom of the page is updated to show the answer codes and values of your responses.

Common Debugging Examples
Nested if() Statements (Conditional Logic)
EM supports the function "if(test,do_if_true,do_if_false)" so that you can perform conditional logic or tailoring. This function can be nested to do the equivalent of "if { } else if { } else { }". EM will let you know if the parentheses are not balanced (e.g., you are missing a closing right parenthesis), or if you have any extra right parentheses. You should try to count the parentheses as you compose long nested if statements, save it, check for syntax errors, and fix them if any are found. Let's check together the below example.
The group of questions used below can be accessed from here: Tailoring survey example.lsg
First, with nothing entered, you just see "Hello."

If you enter a name, it says, "Hello {name}."

If you enter an age, you get a tailored message, depending upon whether you are a pre-school-age child or not:

School aged, teenager, or adult. Here is a teenager who wants to be anonymous:

Here is the logic file of the group. As you can see in the "if-based" question, there are nested if statements based upon the person's age.

When you are originally editing this question, it is likely that at some point, you will have the wrong number of parentheses. Here's what happens if you have too few:

If you hover over the word "if", which is surrounded by a red box, it says "Parentheses not balanced". In this case, there should be four closing parentheses after "already an adult!", but there are only three.
If, on the other hand, you have an extra right parenthesis, it will be surrounded by a red box, like this:

When you are actually editing the question, the question looks like this:
