Comments (16)
This will happen if you have an interpreter with a different config on the stack (in this case, one that has isFailOnUnknownTokens() == false
)
JinjavaInterpreter parentInterpreter = JinjavaInterpreter.getCurrent();
if (parentInterpreter != null) {
renderConfig = parentInterpreter.getConfig();
...
}
JinjavaInterpreter interpreter = globalConfig
.getInterpreterFactory()
.newInstance(this, context, renderConfig);
JinjavaInterpreter.pushCurrent(interpreter);
try {
String result = interpreter.render(template);
renderConfig will get overridden with the parent interpreter's config if there is an interpreter on the stack, rather than just the jinjava.getGlobalConfig()
Try calling JinjavaInterpreter.popCurrent()
before the code block in the StackOverflow question and see if it works properly
from jinjava.
This will happen if you have an interpreter with a different config on the stack (in this case, one that has
isFailOnUnknownTokens() == false
)JinjavaInterpreter parentInterpreter = JinjavaInterpreter.getCurrent(); if (parentInterpreter != null) { renderConfig = parentInterpreter.getConfig(); ... } JinjavaInterpreter interpreter = globalConfig .getInterpreterFactory() .newInstance(this, context, renderConfig); JinjavaInterpreter.pushCurrent(interpreter); try { String result = interpreter.render(template);renderConfig will get overridden with the parent interpreter's config if there is an interpreter on the stack, rather than just the
jinjava.getGlobalConfig()
Try calling
JinjavaInterpreter.popCurrent()
before the code block in the StackOverflow question and see if it works properly
Now I get hostname={{host}} if the context does not have the necessary variable, how to make it throw an error if the required variable is not found in context?
from jinjava.
Are there more details to your setup. The render result should have a blank output and it should have an error in renderResult.getErrors()
. Are there no FATAL errors in your RenderResult?
from jinjava.
Are there more details to your setup. The render result should have a blank output and it should have an error in
renderResult.getErrors()
. Are there no FATAL errors in your RenderResult?
Yesterday I used JinjavaInterpeter.popCurrent(); and everything worked, but today it again clears the file, tell me what might be the problem? I understand that sounds unreasonable but I did even mvn clean, and did Invalidate Cache
from jinjava.
while(JinjavaInterpreter.getCurrent() != null) {
JinjavaInterpreter.popCurrent();
}
Maybe doing this will help.
from jinjava.
while(JinjavaInterpreter.getCurrent() != null) { JinjavaInterpreter.popCurrent(); }Maybe doing this will help.
Does not help.
from jinjava.
Can you reproduce this with a minimal Junit test that you can paste or link here?
from jinjava.
while(JinjavaInterpreter.getCurrent() != null) { JinjavaInterpreter.popCurrent(); }Maybe doing this will help.
If there are no other options, then how to make sure that after rendering hostname={{hostname}} is not replaced with hostname= . You must, if the variable in the context is not found, leave the value as was hostname={{hostaname}} ?
from jinjava.
Can you reproduce this with a minimal Junit test that you can paste or link here?
JUnit4: 4.12
Jinjava: 2.6.0
commons-io: 1.3.2
jackson-annotations: 2.13.2
file with extension .properties
@Test
public void test() throws IOException {
while(JinjavaInterpreter.getCurrent() != null) {
JinjavaInterpreter.popCurrent();
}
JinjavaConfig.Builder config = JinjavaConfig.newBuilder();
config.withFailOnUnknownTokens(true);
Jinjava jinjava = new Jinjava(config.build());
RenderResult renderResult = jinjava.renderForResult(Resources.toString(new File(Resources.getResource(
"test.properties").getPath()).toURI().toURL(), StandardCharsets.UTF_8), new HashMap<>());
String path = Resources.getResource("test.properties").getPath();
List<String> linesList = Files.readLines(new File(path), StandardCharsets.UTF_8);
StringBuilder result = new StringBuilder();
linesList.forEach((str) -> result.append(str + "\n"));
System.out.println("expected: " + result);
System.out.println("actual: " + renderResult.getOutput());
System.out.println("End");
Assert.assertEquals(result.toString(), renderResult.getOutput());
}
from jinjava.
If you want the exception to be thrown, then you'd run:
JinjavaInterpreter interpreter = jinjava.newInterpreter();
interpreter.render(input);
This will throw an UnknownTokenException.
If you're using jinjava.renderForResult()
, then the output should be empty and there should be a TemplateError in renderResult.getErrors()
.
Are you telling me that after running the above code, renderResult.getOutput()
contains hostname=
?
from jinjava.
If you want the exception to be thrown, then you'd run:
JinjavaInterpreter interpreter = jinjava.newInterpreter(); interpreter.render(input);
This will throw an UnknownTokenException.
If you're using
jinjava.renderForResult()
, then the output should be empty and there should be a TemplateError inrenderResult.getErrors()
.Are you telling me that after running the above code,
renderResult.getOutput()
containshostname=
?
No, after running the code above renderResult.getOutput() contains an empty value
- I want the
config.withFailOnUnknownTokens(false)
flagrenderResult.getOutput()
to return
hostname={{hostname}}
if the variable is not found instead ofhostname= .
- If the flag is set in
config.withFailOnUnknownTokens(true)
it threw an error instead of clearing the file, the test above will show
from jinjava.
If you want the exception to be thrown, then you'd run:
JinjavaInterpreter interpreter = jinjava.newInterpreter(); interpreter.render(input);
This will throw an UnknownTokenException.
If you're using
jinjava.renderForResult()
, then the output should be empty and there should be a TemplateError inrenderResult.getErrors()
.Are you telling me that after running the above code,
renderResult.getOutput()
containshostname=
?
- Looks like my mistake was because the blank result was written into a file
renderResult.getOutput()
How do you respond to my first block in the comments above?
from jinjava.
I thought you were wanting it to throw an exception?
If you don't want to throw an exception, and instead leave the expression as-is, you could combine the dynamic variable resolver #572 with using Eager Execution. Use a dynamic variable resolver that maps all string values to a DeferredValue.instance()
.
You can turn on Eager execution mode by doing config.withExecutionMode(EagerExecutionMode.instance())
.
Combining these things will make it so that any value that does not exist on the context will be treated as a deferred value, and it will not be evaluated, which sounds like what you are looking for.
For example if you had:
{% if hostname %}
hostname={{hostname}}
{% else %}
hostname={{ 'none' }}
{% endif %}
the output would be:
{% if hostname %}
hostname={{hostname}}
{% else %}
hostname=none
{% endif %}
from jinjava.
Я думал, вы хотите, чтобы он выдал исключение? Если вы не хотите генерировать исключение и вместо этого оставляете выражение как есть, вы можете комбинировать преобразователь динамических переменных #572 с использованием Eager Execution. Используйте преобразователь динамических переменных, который сопоставляет все строковые значения с файлом
DeferredValue.instance()
. Вы можете включить режим выполнения Eager, выполнивconfig.withExecutionMode(EagerExecutionMode.instance())
. Комбинация этих вещей сделает так, что любое значение, которое не существует в контексте, будет рассматриваться как отложенное значение и не будет оцениваться, что звучит как то, что вы ищете. Например, если у вас было:{% if hostname %} hostname={{hostname}} {% else %} hostname={{ 'none' }} {% endif %}
вывод будет:
{% if hostname %} hostname={{hostname}} {% else %} hostname=none {% endif %}
Thank you, that solved my problem
from jinjava.
I thought you were wanting it to throw an exception? If you don't want to throw an exception, and instead leave the expression as-is, you could combine the dynamic variable resolver #572 with using Eager Execution. Use a dynamic variable resolver that maps all string values to a
DeferredValue.instance()
. You can turn on Eager execution mode by doingconfig.withExecutionMode(EagerExecutionMode.instance())
. Combining these things will make it so that any value that does not exist on the context will be treated as a deferred value, and it will not be evaluated, which sounds like what you are looking for. For example if you had:{% if hostname %} hostname={{hostname}} {% else %} hostname={{ 'none' }} {% endif %}
the output would be:
{% if hostname %} hostname={{hostname}} {% else %} hostname=none {% endif %}
Hello, and how to make jinjava not fall with the error com.hubspot.jinjava.interpret.UnknownTokenException: Unknown token found: Unclosed comment
on variables such as: hostname={#hostname}
?
file contains only line hostname={#hostname}
from jinjava.
Hello, and how to make jinjava not fall with the error com.hubspot.jinjava.interpret.UnknownTokenException: Unknown token found: Unclosed comment on variables such as: hostname={#hostname}?
file contains only line hostname={#hostname}
No way to avoid that one. {#hostname}
is invalid jinja syntax because {#
and #}
are used for comments. If you open a comment, you need to close it as well. Jinjava allows you to specify custom token symbols though, so you can remove the comment symbols if you want to, rather than using DefaultTokenScannerSymbols
from jinjava.
Related Issues (20)
- Release? HOT 1
- Is there a way to not render a variable that is not defined?
- [range] unable to modify existing variable inside a range loop HOT 1
- Macros should not generate a breakline
- "list" filter is not working as expected for arrays HOT 1
- Java 17.0.6 + jinjava 2.5.0 function: ".replace" HOT 1
- multi map convert issue HOT 1
- Expected Exception during execution
- How to retrieve the variables in a template HOT 1
- E/AndroidRuntime: FATAL EXCEPTION: main
- Template Render to keep unresolved variables as-is in the output HOT 4
- Update dependencies with vulnerabilities
- Dependency org.yaml:snakeyaml, leading to CVE problem
- for else control structure doesn't seem to be supported HOT 1
- Engine performance HOT 2
- render template that it is contains one '\r\n' string will return more than one
- Can Dict key be an integer? HOT 2
- CVEs in current version: 2.7.0
- time for 2.7.1 / 2.8.0 ?
- Unexpected behavior comparing empty strings to 0
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jinjava.