How can I convert `str` type to a `content` type (string to content)?

Hi there. Newbie question here.
The str type has many facilities such as regex manipulation not available for content material.
Let’s assume there’s a need to process a certain text as a string as we do with a template and to compose the resulting text from the union of the model with data. With this objective in mind, I haven’t been able to compose a string as markup text. For example, in the following code, I would expect the string to be typesetted as content, but it’s not the case.

#let s = "This is a *string* defining $pi$ as $3.14$!"
#s

immagine

Expected result:
immagine

How do that?
Thanks

Hello @Roberto,

This could be achieved with the use of the Evaluate Function:

#let s = "This is a *string* defining $pi$ as $3.14$!"
#s
#eval(s, mode: "markup")

image

1 Like

Thank you @vmartel08. Any perfomance issue with the use of eval function in order to content conversion?
Docs defines eval as last resource.

Well, as you can read in the doc:

This function should only be used as a last resort.

I’m not an expert of the Typst compiler internals but I would think that converting text to content should be nearly cost-less while converting content to text is more costly. Someone with more expertise should probably answer this part.

May I suggest you move your question to the Questions category?

1 Like

In your code block, you should use typ code identifier instead of typc.

I’m not sure if there is a noticeable cost to this, but the scope is separate, so if something is referenced from outside, it must be specified.

eval() is the only way to render Typst examples, which has been done by many people, so I don’t think it’s that bad. There is `eval` drops all warnings · Issue #6067 · typst/typst · GitHub, which was fixed recently.

1 Like

I read the “should only be used as a last resort” as “use the markup syntax
[ .. ] unless you have a good reason not to”. I too have seen it used throughout various code examples here, on GitHub and on the Typst Discord.

@Roberto please make sure you follow-up by either marking :white_check_mark: the post you found the most useful in answering your question to help others in the future.