Replace line break - typo3

In Fluid Template and tx_news, I need to replace line breaks with "\n" for passing into JavaScript function.
If a JavaScript string contains line break, console will print "Unexpected token."
<a onclick="doSomething('{newsItem.bodytext}');">Click me</a>
How can you replace line breaks with "\n" in this example?

AS urbantrout already wrote: you can write an own viewhelper in PHP.
But you also can use a TypoScript-Viewhelper:
<a onclick="doSomething('{newsItem.bodytext -> f:cObject(typoscriptObjectPath: \'lib.nlReplace\')}');">Click me</a>
(as you are in a string you need to escape the inner ')
and some TypoScript like
lib.nlReplace = TEXT
lib.nlReplace {
current = 1
stdWrap.replacement {
1 {
search = #\n#
replace = \\n
useRegExp = 1
}
}
}

You could write your own ViewHelper and use it like this:
{namespace ns=Vendor\ExtensionName\ViewHelpers}
<a onclick="doSomething('{newsItem.bodytext -> ns:viewhelperName()}');">Click me</a>
More infos here: Developing a custom ViewHelper

Related

How to remove strings at left of "-" in filename in TYPO3 Fluid?

Using TYPO3 8 LTS, we got many standardized filenames like:
ABC_105-Report.pdf
DEFGH_110-Brochure.ppt
We need to remove whatever is at left of "-" so it becomes a list like this in TYPO3 Frontend:
Report.pdf
Brochure.ppt
We are already using VHS Viewhelpers which contains Format:Eliminiate, Substring so it may be part of the solution.
One possible solution is VHS: Format / PregReplaceViewHelper.
<f:alias map="{filenames: {
0: 'ABC_105-Report.pdf',
1: 'DEFGH_110-Brochure.ppt',
2: 'FilenameWithoutMagicChar.jpg',
3: 'Multiple-Magic-Chars.jpg'}}">
<ul>
<f:for each="{filenames}" as="filename">
<li>
{v:format.pregReplace(
subject: filename,
pattern: '/^[^-]*-/',
replacement: ''
)}
</li>
</f:for>
</ul>
</f:alias>
Result:
Report.pdf
Brochure.ppt
FilenameWithoutMagicChar.jpg
Magic-Chars.jpg
If 'Chars.jpg' is required instead of 'Magic-Chars.jpg', the regular expression is /-.*/.
a very basic typoscript viewhelper:
in fluid:
<f:cObject typoscriptObjectPath="lib.filenameStub" data="{filename}" />
in typoscript:
lib.filenameStub = TEXT
lib.filenameStub {
current = 1
split {
max = 2
token = -
returnKey = 1
}
}

JAVASCRIPT: Replace a single character into a <p>

I've got a word in an HTML paragraph. For example 'string':
<p id="myWord">string</p>
I want to change only a character of that word. For example 'strong':
So I add an html button that calls a function:
<button onclick="myFunction">replace 'i'</button>
the function in JS is this but it can't access to the fourth character of myWord:
function myFunction{
document.getElementById("myWord[3]").innerHTML = 'o';
}
Here is the unWorking fiddle: https://jsfiddle.net/su3Lrezr/4/
How can I access to a index of a word in a html paragraph? I already tried to convert myWord into an array with split() method but it doesn't work.
Thanks everybody
Array method:
You'll want to split the string at value 'i' Then rejoin them together with an 'o' in the middle. Then update your innerHTML. You will need the split() function. This will work:
function myFunction(){
var word = document.getElementById('myWord').innerHTML;
var result = word.split('i');
var newword = result[0] + "o" + result[1];
document.getElementById('myWord').innerHTML = newword;
}
Also, as a commenter has mentioned your syntax for calling functions is wrong. You must call functions like this: myFunction() and declare them like this: function myFunction(){ }

Typoscript: how do I add a parameter to all links in the RTE?

I want to add a parameter to all links entered in the RTE by the user.
My initial idea was to do this:
lib.parseFunc_RTE.tags.link {
typolink.parameter.append = TEXT
typolink.parameter.append.value = ?flavor=lemon
}
So for example:
http://domain.com/mypage.php
becomes
http://domain.com/mypage.php?flavor=lemon
which sounds great -- as long as the link does not already have a query string!
In that case, I obviously end up with two question marks in the URL
So for example:
http://domain.com/prefs.php?id=1234&unit=moon&qty=300
becomes
http://domain.com/prefs.php?id=1234&unit=moon&qty=300?flavor=lemon
Is there any way to add my parameter with the correct syntax, depending on whether the URL already has a query string or not? Thanks!
That would be the solution:
lib.parseFunc_RTE.tags.link {
typolink.additionalParams = &flavor=lemon
}
Note that it has to start with an &, typo3 then generates a valid link. The parameter in the link also will be parsed with realURL if configured accordingly.
Edit: The above solution only works for internal links as described in the documentation https://docs.typo3.org/typo3cms/TyposcriptReference/Functions/Typolink/Index.html
The only solution that works for all links that I see is to use a userFunc
lib.parseFunc_RTE.tags.link {
typolink.userFunc = user_addAdditionalParams
}
Then you need to create a php script and include in your TS with:
includeLibs.rteScript = path/to/yourScript.php
Keep in mind that includeLibs is outdated, so if you are using TYPO3 8.x (and probably 7.3+) you will need to create a custom extension with just a few files
<?php
function user_addAdditionalParams($finalTagParts) {
// modify the url in $finalTagParts['url']
// $finalTagParts['TYPE'] is an indication of link-kind: mailto, url, file, page, you can use it to check if you need to append the new params
switch ($finalTagParts['TYPE']) {
case 'url':
case 'file':
$parts = explode('#', $finalTagParts['url']);
$finalTagParts['url'] = $parts[0]
. (strpos($parts[0], '?') === false ? '?' : '&')
. 'newParam=test&newParam=test2'
. ($parts[1] ? '#' . $parts[1] : '');
break;
}
return '<a href="' . $finalTagParts['url'] . '"' .
$finalTagParts['targetParams'] .
$finalTagParts['aTagParams'] . '>'
}
PS: i have not tested the actual php code, so it can have some errors. If you have troubles, try debugging the $finalTagParts variable
Test whether the "?" character is already in the URL and append either "?" or "&", then append your key-value pair. There's a CASE object available in the TypoScript Reference, with an example you can modify for your purpose.
For anyone interested, here's a solution that worked for me using the replacement function of Typoscript. Hope this helps.
lib.parseFunc_RTE.tags.link {
# Start by "replacing" the whole URL by itself + our string
# For example: http://domain.com/?id=100 becomes http://domain.com/?id=100?flavor=lemon
# For example: http://domain.com/index.html becomes http://domain.com/index.html?flavor=lemon
typolink.parameter.stdWrap.replacement.10 {
#this matches the whole URL
search = #^(.*)$#i
# this replaces it with itself (${1}) + our string
replace =${1}?flavor=lemon
# in this case we want to use regular expressions
useRegExp = 1
}
# After the first replacement is done, we simply replace
# the first '?' by '?' and all others by '&'
# the use of Option Split allow this
typolink.parameter.stdWrap.replacement.20 {
search = ?
replace = ? || & || &
useOptionSplitReplace = 1
}
}

Accessing bind-at values from a snippet in Lift

I have a template that looks like this:
<lift:surround name="default" at="page-content">
<lift:bind-at name="page-title">Home</lift:bind-at>
...
</lift:surround>
The default template looks like this:
<html>
<head>
<title>Title Prefix | </title>
</head>
<body>
<h1><lift:bind name="page-title" /></h1>
<div id="page-content">
<lift:bind name="page-content" />
</div>
</body>
</html>
I want to use a snippet to replace the <title> content with a string that combines "Title Prefix" and the value of <lift:bind-at name="page-title"> (ie: "Home"). I want to contine to use that same value inside the <h1> in the <body>
How can I access a bind-at value from within a snippet that's used in the surrounding template?
I don't believe you can do what you are looking to do with bind-at directives, or at least, I haven't found a way. You should be able to use a snippet to accomplish something similar though.
For example, if you are using SiteMap, the following should be roughly equivalent.
class TitleSnippet {
//Store the value in a requestVar
private var titleVar:String = ""
def first = {
//Retrieve the title for the current Loc as defined in the Sitemap
val locTitle = for (request <- S.request;
loc <- request.location) yield loc.title
//Retrieve the text portion of the tag, and append it to the sitemap title.
//If no sitemap title exists, just display the text
"* *" #> { ns =>
val myTitle = locTitle.map{ t =>
"%s | %s".format(ns.text, t)
} openOr ns.text
titleVar = myTitle
Text(myTitle)
}
}
def title = {
"* *" #> titleVar
}
}
Then, in your template, all you'd have to do is say:
<title data-lift="TitleSnippet.first">Home</title>
So, if we had a page defined like this in the sitemap:
Menu("Sub Page 1") / "subpage"
If everything worked, you should see a title like: <title>Home | Sub Page 1</title> and if you need it elsewhere on the page, all you would have to do is: <h1 data-lift="TitleSnippet.title"></h1>.
If you need access from other snippets, you can also break out titleVar into a companion object and use a RequestVar.

ModX Evolution: pass variable from url to form text field on page load

I need to pass string from url:
../page.html?code=123456
to a form (eform snippet in modx)
just once is page loaded (link with url and parameter)
Thanks for answer...
My solution:
1. create a new snippet called GetCode
<?php
if( !function_exists('eformGetCode') ) {
function eformGetCode(&$fields,&$templates){
global $modx;
$code = strip_tags($_GET['codeID']);
$templates['tpl']=str_replace('[+display_code+]',$code,$templates['tpl']);
return true; } }
return '';
?>
2. Add eform call (and snippet) on webpage:
[!GetCode!]
[!eForm? ... ... &eFormOnBeforeFormParse=`eformGetCode` !]
3. In eform chunk with form code add line:
<input name="code" id="code" value="[+display_code+]" eform="::1:" type="text"/>
5. Now when you put parametr in url like:
..../page.html?code=123456
this should appear in form.
you would do this exactly like you would in php..
$myVar = $_GET['code'];
If you are having issues, take a peek in the modx error logs...
-sean
Solution by KudyKam is better than official solution in MODX docs, in which they use a database. http://wiki.modxcms.com/index.php/Populate_eform_with_dynamic_data