Fevol/obsidian-translate

How to use it with the Templator plugin?

Closed this issue · 4 comments

I've been using it quite well.
I have one request.

It would be nice if there was a way to use it in conjunction with the Templator plugin.

Example template expected conversion
<%*
let engTexg = "I want to translate"
targetText = { some action }
%>

It would be really useful to be able to do this.

Could you check if the following works for you?

let engText = "I want to translate";
let sourceLanguage "auto";
let targetLanguage = "zh";

const translator = app.plugins.plugins['translate']?.translator;
let outputText = '';
if (translator && translator.valid) {
	outputText = await translator.translate(engText, sourceLanguage, targetLanguage).translation;
}

<%*
let engText = "I want to translate";
let sourceLanguage = "auto";
let targetLanguage = "zh";

const translator = this.app.plugins.plugins['translate'].translator;
let outputText = '';
if (translator && translator.valid) {
outputText = await translator.translate(engText, sourceLanguage, targetLanguage).translation;
}
-%>
I don't know much about computer coding.

I tried this in a template format and got an error.
I get an error on the line below

outputText = await translator.translate(engText, sourceLanguage, targetLanguage).translation;

I don't know how to use the function ?? and how to fix the error.

I apologise for the delay, I wanted to fully fix the API before I investigated this further.

With the new version (releasing soon), you could make a template like this:

<%*
let engText = "I want to translate";
let sourceLanguage = "auto";  
let targetLanguage = "zh";

const api = app.plugins.plugins['translate'].api;
if (api?.canTranslate) {  
	const output = await api.translate(engText, sourceLanguage, targetLanguage); 
	console.log(output)
	if (output.status_code !== 200)
	    new Notice(output.message);
	else
	    tR += output.translation;
}
%>

(tR is what Templater will display, in this case)

Let me know if this (doesn't) work! Since I'm not very experienced with Templater myself, you may also want to ask in the Discord if there is a better/cleaner method.

Thank you very much.
code working fine